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 pref开发者_如何学Pythoner 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)?
The biggest reason not to use the 2nd form is that you'll end up eliminating anything else that existed in the prototype before you assign it. If that isn't something you're concerned with there's no reason not to declare it the way you've demonstrated.
I think there is another drawback of using the "assignment" form to the prototype
property: You will likely wipe out the prototype.__proto__
property (prototype chain) when you're dealing with the "pseudo-classical" inheritance.
Of course, one could argue there is a fishy way to remedy this, which is to attach the __proto__
property yourself to connect the chain again. But forgetting doing this will break the code if you call the parent method. See my fiddle here: http://jsfiddle.net/glenn/v5Yub/
Conclusion: The "assignment" form might look simpler / cleaner, but the "property" form is safer.
I think the best way to assign prototype of a function without destroying the current prototype by using Object.assign.
function myFunction() {
}
Object.assign(myFunction.prototype, {
say(str) { return str },
greet(name) { return "Hello " + name}
})
Since EcmaScript2015 there is little reason to fiddle with the prototype
property any more.
The class
syntax provides what is needed in a more intuitive syntax:
class MyClass {
constructor() { }
foo() { ... }
bar() { ... }
}
...and when a longer prototype chain is needed:
class MySuperClass {
constructor() { }
foo() { ... }
bar() { ... }
}
class MyClass extends MySuperClass{
constructor() { }
gah() { ... }
}
精彩评论