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

前端 未结 7 1492
陌清茗
陌清茗 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:54

    In short, use method 2 for creating properties/methods that all instances will share. Those will be "global" and any change to it will be reflected across all instances. Use method 1 for creating instance specific properties/methods.

    I wish I had a better reference but for now take a look at this. You can see how I used both methods in the same project for different purposes.

    Hope this helps. :)

提交回复
热议问题