Search code examples
javascriptprototypethisself

Javascript: Self and This


Can anyone explain why do I get different values of self and this? Where self is a reference to this.

function Parent(){
   var self = this;
   this.func = function(){
      // self.a is undefined
      // this.a is 'Test'
      console.log(self.a, this.a);
   }
}

function Child(x){
   this.a = x;
}

Child.prototype.__proto__ = new Parent;
var ch = new Child('Test');
ch.func();

I've been using self on project and it's my first time to have this issue.


Solution

  • This is because self refers to an instance of Parent, but only instances of Child have an a property.

    function Parent(){
       var self = this; // this is an instance of Parent
       this.func = function(){
          console.log(self.a, this.a);
       }
    }
    
    function Child(x){
        this.a = x; // Instances of Child have an `a` property
    }
    
    Child.prototype.__proto__ = new Parent;
    var ch = new Child('Test');
    
    ch.func(); // Method called in context of instance of Child
    

    So when you call func on an instance of Child, this refers to that instance. That's why this.a gives you the correct value inside func.