admin管理员组

文章数量:1279175

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.

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.

Share Improve this question asked Feb 25, 2013 at 9:27 KevinKevin 5025 silver badges15 bronze badges 4
  • self and this are no longer referring to the same object. The following link may be helpful : stackoverflow./questions/962033/… – Chetter Hummin Commented Feb 25, 2013 at 9:31
  • ô the joy of javascript call context ! – benzonico Commented Feb 25, 2013 at 9:32
  • In func, it seems like self points to the Parent, but this points to the Child. – Blender Commented Feb 25, 2013 at 9:33
  • Thanks for the answers. This is why I like javascript, very different. Now I need to be more careful on nested callbacks. – Kevin Commented Feb 25, 2013 at 10:41
Add a ment  | 

2 Answers 2

Reset to default 9

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.

Within func, this refers to an instance of Child.

Child.prototype.__proto__ = new Parent;

The prototype of Child is set to an instance of Parent. So when ch.func() is invoked, func() is on the prototype chain of Child, but is invoked in the context of ch which is an instance of Child

self is still referring to the instance of Parent which does not have an attribute a

To further illustrate:

var p = new Parent();

// this.a is undefined because this is an instance of Parent
p.func(); // undefined undefined

本文标签: prototypeJavascript Self and ThisStack Overflow