Are prototypes bad in JavaScript?

前端 未结 2 386
离开以前
离开以前 2021-01-31 11:11

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

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 11:49

    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.

提交回复
热议问题