Prototype vs. Not, what are benefits?

前端 未结 3 736
猫巷女王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:34

    The primordial differrence is that in your first example, without prototype, the getSecret and setSecret function implementation will reside on every instance of spy1.

    On your second example, the functions are defined on the prototype, and all instances refer to them directly, you can test it:

    var bond = new spy1("007"),
        bond2 = new spy1("007");
    
    bond.getSecret === bond2.getSecret; // <-- false since they are two functions
    
    var smart = new spy2("86"),
        smart2 = new spy2("86");
    
    
    smart.getSecret === smart2.getSecret; // <-- true since is the same function
                                          // on all instances
    

    Also note what @T.J. commented, in your second example, using the prototype, you don't have access to the constructor function closure, and for that you are making a window.secret global variable.

    If you intend to work with privileged methods, extending the prototype is not an option, all the methods that need access to the variables defined within the scope of the constructor function need to be declared inside of it...

    See also: Closures.

提交回复
热议问题