Are prototypes bad in JavaScript?

2020-05-17 09:27发布

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

Do not extend the prototypes of any objects, especially native ones. There is a special place 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?

2条回答
家丑人穷心不美
2楼-- · 2020-05-17 09:59

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.

查看更多
趁早两清
3楼-- · 2020-05-17 10:13

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..

查看更多
登录 后发表回答