簡體   English   中英

未捕獲的TypeError:無法讀取未定義的屬性“ x”

[英]Uncaught TypeError: Cannot read property 'x' of undefined

我在上面獲得此代碼的錯誤(第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);

但電話像:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM