In JavaScript we can assign properties to a function's prototype or set its prototype object directly:
var MyClass = function() { };
// The "property" form...
MyClass.prototype.foo = function() { ... };
MyClass.prototype.bar = function() { ... };
MyClass.prototype.gah = function() { ... };
// OR the "assignment" form...
MyClass.prototype = {
foo:function() { ... },
bar:function() { ... },
gah:function() { ... }
};
I personally prefer the assignment form because you can easily wrap the object in a closure (e.g. to hide "private" objects) and if you later decide to change the name of "MyClass" you've only got to find two spots instead of potentially dozens. (Of course, the same could be said for the "property" form by using and calling a function which takes the existing prototype as an argument but the "assignment" form seems more direct in my opinion.)
Is there a strong reason to use one form instead of the other?
[Edit]
As commenter @Raynos mentions, the second form (assignment) clobbers the prototype.constructor
attribute, which should be set to the MyClass function (and is by default in the first form [property]). Are there any real drawbacks to this (other than the the fact that the property isn't set)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…