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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With