Reputation: 11
Iam getting error above for this code (line 9):
pair = function(x,y){
this.x = x;
this.y = y;
}
alpha = function(){
this.field = new pair(0,0);
this.fun = function(){
console.log(this.field.x);
}
}
function beta(para){
para();
}
beta(new alpha().fun);
but the call like:
new alpha().fun();
works fine.
Could someone explain what's going on in this case?
Upvotes: 0
Views: 327
Reputation: 382092
That's because the function isn't called with the right context (this
).
You can use bind
to ensure it's correct :
this.fun = (function(){
console.log(this.field.x);
}).bind(this);
You could also use the closure to store the value of this
:
alpha = function(){
var a = this;
this.field = new pair(0,0);
this.fun = function(){
console.log(a.field.x);
}
}
Upvotes: 4