Adding new properties to constructor function without .prototype

后端 未结 3 1649
感情败类
感情败类 2020-12-13 05:31

when I have function I want to use as a constructor, say:

function clog(x){
    var text = x;
    return console.log(text );
}

And I have m

3条回答
  •  悲&欢浪女
    2020-12-13 06:04

    Adding a clog.alert function would simply a attach static function to the clog object. It will not be inherited and will not have access to the instance created with new clog(); in the alert function.

    Adding clog.prototype.alert will make the new clog(); object you create inherit the function, and you will also have access to the instance inside using the this keyword.

    function John() {
        this.id = 1;
    }
    
    John.doe = function() {
      console.log(this);
      console.log(this.id); // undefined
    }
    
    John.prototype.doe = function() {
        console.log(this);
    };
    
    John.doe(); // the John object
    
    var me = new John();
    me.doe(); // the instance, inherited from prototype
    console.log(me.id); // 1
    

提交回复
热议问题