Javascript:自我和这

Kev*_*vin 7 javascript prototype this self

任何人都可以解释为什么我得到不同的自我和这个值?自我是对此的参考.

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();
Run Code Online (Sandbox Code Playgroud)

我一直在项目上使用self,这是我第一次遇到这个问题.

Jam*_*ice 9

这是因为self引用了一个实例Parent,但只有Child具有a属性的实例.

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
Run Code Online (Sandbox Code Playgroud)

因此,当您调用func实例时Child,请this引用该实例.这就是为什么this.a在里面给你正确的价值func.