Javascript:Self和这个

Javascript:Self和这个,javascript,prototype,this,self,Javascript,Prototype,This,Self,有人能解释为什么我对自我和这个有不同的价值观吗?其中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.protot

有人能解释为什么我对自我和这个有不同的价值观吗?其中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();

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

这是因为
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

因此,当您对
Child
的实例调用
func
时,
引用该实例。这就是为什么
this.a
func
中为您提供了正确的值,在
func
中,
引用了
的实例

Child.prototype.__proto__ = new Parent;
Child
的原型被设置为
Parent
的实例。因此,当调用
ch.func()
时,
func()
位于
Child
的原型链上,但在
ch
的上下文中调用,后者是
Child
的实例

self
仍在引用没有属性
a

进一步说明:

var p = new Parent();

// this.a is undefined because this is an instance of Parent
p.func(); // undefined undefined
var myObject={
福:“酒吧”,
func:function(){
var self=这个;
console.log(“outer func1:this.foo=“+this.foo);//条
console.log(“外部函数2:self.foo=“+self.foo);//条
(功能(){
console.log(“内部func3:this.foo=“+this.foo);//取消查找
console.log(“内部func4:self.foo=“+self.foo);//条
}());
}
};
myObject.func()
函数Foo(){
this.bar='bar';
归还这个;
}
Foo.prototype.test=函数(){return 1;}
功能条(){
this.bro='bro';
归还这个;
}
Bar.prototype.test2=函数(){return 2;}
函数2(){
Foo.call(这个);
酒吧。叫(这个);
归还这个;
}
//log(Object.create(Bar.prototype));
var combine=Object.create(Foo.prototype);
//控制台日志(合并);
$.extend(合并,Object.create(Bar.prototype));
$.extend(combine,Object.create(Foo.prototype));
Cool2.prototype=Object.create(合并);
//Cool2.prototype.constructor=Cool2;
var cool=新的Cool2();
console.log(cool.test());//1.
log(cool.test2())//2.
console.log(cool.brow)//bro
console.log(cool.bar)//bar
console.log(Foo的冷实例)//真的
console.log(棒的冷实例)//假的

self和它不再指同一个对象。以下链接可能会有所帮助:javascript调用上下文的乐趣!在
func
中,似乎
self
指向
父项
,但
指向
子项
。感谢您的回答。这就是为什么我喜欢javascript,非常不同。现在我需要更加小心嵌套回调。不过,在内部函数中,这不再指myObject。因此,this.foo在内部函数中是未定义的,而对局部变量self的引用仍在范围内,可以在那里访问。请在回答中添加解释