Defining methods via prototype vs using this in the constructor - really a performance difference?

前端 未结 7 1421
陌清茗
陌清茗 2020-11-22 12:06

In JavaScript, we have two ways of making a \"class\" and giving it public functions.

Method 1:

function MyClass() {
    var privateInstanceVariable         


        
7条回答
  •  情话喂你
    2020-11-22 12:45

    You might not have considered this, but putting the method directly on the object is actually better in one way:

    1. Method invocations are very slightly faster (jsperf) since the prototype chain does not have to be consulted to resolve the method.

    However, the speed difference is almost negligible. On top of that, putting a method on a prototype is better in two more impactful ways:

    1. Faster to create instances (jsperf)
    2. Uses less memory

    Like James said, this difference can be important if you are instantiating thousands of instances of a class.

    That said, I can certainly imagine a JavaScript engine that recognizes that the function you are attaching to each object does not change across instances and thus only keeps one copy of the function in memory, with all instance methods pointing to the shared function. In fact, it seems that Firefox is doing some special optimization like this but Chrome is not.


    ASIDE:

    You are right that it is impossible to access private instance variables from inside methods on prototypes. So I guess the question you must ask yourself is do you value being able to make instance variables truly private over utilizing inheritance and prototyping? I personally think that making variables truly private is not that important and would just use the underscore prefix (e.g., "this._myVar") to signify that although the variable is public, it should be considered to be private. That said, in ES6, there is apparently a way to have the both of both worlds!

提交回复
热议问题