Define Constructor Prototype With Object Literal
Solution 1:
I would say there wouldn't be much of a difference. Using an object literal to assign to the Object.prototype is something you can't do if you're assigning the prototype within the constructor (which can be usefull sometimes).
Maybe you should write a little performance test using jsperf.com.
Solution 2:
var example = new MyConstructor();
under method 1:
example.constructor === MyConstructor;
under method 2:
typeof(example.constructor) === 'undefined';
The prototype object that comes with a function has a property constructor
that points back to the function. If you assign to the proprties of that object, you keep the constructor
property. If you overwrite the prototype
property with a new object, you lose the constructor
property.
The performance difference is minimal. Because constructor
is so fragile, you can't really trust it, so I don't bother to preserve it.
Solution 3:
You should use the method 1. Using the method 2, everytime you create a new instance, you will "re-create" the methods, since they are inside the constructor.
Solution 4:
Speaking further about the readability of your code,
method 1 is better than method 2.
Method 2 spend one more indentation. So it cause difficulty for reading codes.
Additionally, in my case, I can't inference that whether this function is prototype method or just static member function when we see a function name part in the lower part of codes.
Personally, in conclusion, I prefer method 2 if there not be much of a difference about performance.
Thanks!
Post a Comment for "Define Constructor Prototype With Object Literal"