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 likeself
points to theParent
, butthis
points to theChild
. – 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
2 Answers
Reset to default 9This 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
版权声明:本文标题:prototype - Javascript: Self and This - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741248889a2365418.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论