Defining a Javascript prototype

后端 未结 5 1760
陌清茗
陌清茗 2020-11-22 10:05

What are the functional differences between the following two Javascript prototypes, and are there any benefits for choosing one over the other?

Option 1:

5条回答
  •  花落未央
    2020-11-22 10:34

    Any existing instances of the constructor will continue pointing to the old prototype object. Any new instances created will point to the new prototype object.


    The advantages of option 1 over option 2 are simply that you don't have to re-establish constructor property and you save one indentation level which is huge for me.

    To save repetition, I just assign the property to a local variable:

    var method = Person.prototype;
    
    method.getAge = function() {
        return this.age;
    };
    
    method.getName = function() {
        return this.name;
    };
    

    Also common choices are fn (jQuery) and p which are even shorter than method.

提交回复
热议问题