开发者

Are prototypes bad in JavaScript?

In Felix's Node.js Style Guide it says:

Do not extend the prototypes of any objects, especially native ones. There is a special plac开发者_如何转开发e in hell waiting for you if you don't obey this rule.

This article also made me question the uses of prototypes. If you are going to add a method later on in the code, why not just add it in the original constructor?

So, when is it ever necessary to extend the prototype of an object?


No, prototypes are not bad. Quite the opposite, JavaScript is a prototypal language and prototypes are how you are supposed to extend objects.

The quote is against extending Object.prototype specifically. Not "An object's prototype". Everything in JavaScript inherits from Object, so messing with its prototype effects everything. It breaks for(var n in obj){ loops and is just annoying.

That's the only thing against prototypes -- they show up in for-in loops. Other than that, they are, BY FAR, the best performing way to extend objects in JS.

As for why -- Adding objects in the constructor, say:

function myClass(){
    this.someMethod = function(){ ... }
}

means you will have a seperate function for every instance of the class. Doing it via a prototype:

myClass.prototype.someMethod = function(){ ... }

means there will only ever be one copy of that function. Much more memory efficient, and allows for hot-editing of the language. Let's say you want to edit String.prototype, for instance:

String.prototype.trim = function(){ ... }

If you just added that to the constructor somehow, existing strings would not have the .trim() method, so the code: navigator.userAgent.trim() would not work since navigator.userAgent was defined before you added your trim() method.

And that article is just Tim being anal and paranoid. Ignore it :) As long as you don't forget to type new myClass() instead of just myClass(), you won't have any issues.


Do not extend the prototypes of any objects, especially native ones.

When you extend native objects, like for example string that could be a problem because users are expecting some behavior from that object, but are getting different results. They could get a hard time debugging this..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜