Prototype vs. Not, what are benefits?

前端 未结 3 739
猫巷女王i
猫巷女王i 2020-12-19 04:18

Here I made two objects; one has accessor methods created in the constructor, the other in the prototype. Why would one choose one of these over the other?

f         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-19 04:43

    In your first example, you're creating new functions for each instance of the object whenever you instantiate a new one. In the second, only a single copy of the function is created which is used by all the instances.

    The second way can save memory. You can also use prototype chaining to implement inheritance.

    Btw, your second example won't work as written. the secret variable in spy2 is local to the constructor. In the setSecret and getSecret functions in the prototype, you're accessing a single global variable.

提交回复
热议问题