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?
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 fromObject
, so messing with its prototype effects everything. It breaksfor(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:
means you will have a seperate function for every instance of the class. Doing it via a prototype:
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:
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 sincenavigator.userAgent
was defined before you added yourtrim()
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 justmyClass()
, you won't have any issues.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..