Javascript 未捕获类型错误:无法读取属性';x';未定义的

Javascript 未捕获类型错误:无法读取属性';x';未定义的,javascript,Javascript,Iam获取上述代码错误(第9行): 但是电话是这样的: new alpha().fun(); 很好 有人能解释一下在这种情况下发生了什么吗?这是因为没有使用正确的上下文调用函数(this) 您可以使用bind确保其正确性: this.fun = (function(){ console.log(this.field.x); }).bind(this); 您还可以使用闭包来存储this的值: alpha = function(){ var a = this; this.fiel

Iam获取上述代码错误(第9行):

但是电话是这样的:

new alpha().fun();
很好


有人能解释一下在这种情况下发生了什么吗?

这是因为没有使用正确的上下文调用函数(
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);
   }
}

这是因为没有使用正确的上下文调用函数(
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);
   }
}