Difference between adding function to prototype and object literal in javascript

后端 未结 2 1333
野性不改
野性不改 2021-02-07 06:54

If I have a constructor Quo

var Quo = function (string) {
     this.status = string;
};

and then made a new object using var

2条回答
  •  故里飘歌
    2021-02-07 07:22

    When you define a function, it has a property prototype that is used as the [[prototype]] of all of the objects it creates using the new keyword. When you add members to Quo.prototype, all objects created using new Quo() will be able to read the member as if they had it (through their [[prototype]], namely Quo.prototype). On the other hand, if you assign members to Quo directly, you can only access them through Quo itself.

    Example:

    var Quo = function (status) {
        this.status = status;
    }
    
    Quo.status = "enlightened";
    
    Quo.get_status = function() {
        return this.status;
    }
    
    Quo.prototype.get_status = function() {
        return this.status;
    }
    
    var quo = new Quo("confused");
    
    Quo.get_status(); // "enlightened"
    quo.get_status(); // "confused"
    

提交回复
热议问题