问题
Which method below is best to define a constructor prototype and why?
Method 1:
MyConstructor.prototype.myFunction1 = function(){};
MyConstructor.prototype.myFunction2 = function(){};
Method 2:
MyConstructor.prototype = {
myFunction1: function(){},
myFunction2: function(){}
};
I'm mostly concerned about speed. Thanks!
回答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.
回答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.
回答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.
回答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!
来源:https://stackoverflow.com/questions/4848221/define-constructor-prototype-with-object-literal