2014-01-10 33 views
0

荫的获得上述错误代码(9号线):遗漏的类型错误:无法读取属性 'X' 未定义

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); 

但呼叫,如:

new alpha().fun(); 

工作正常。

有人可以解释在这种情况下发生了什么?

回答

4

这是因为函数没有用正确的上下文调用(this)。

您可以使用bind,以确保它是正确的:

this.fun = (function(){ 
    console.log(this.field.x); 
}).bind(this); 

你也可以使用封存储的this值:

alpha = function(){ 
    var a = this; 
    this.field = new pair(0,0); 
    this.fun = function(){ 
     console.log(a.field.x); 
    } 
} 
相关问题