2014-06-30 74 views
-3

財產「推」我可以在控制檯中調用的,但不是當我按一下按鈕,當一個項目推到價格陣列..遺漏的類型錯誤:無法讀取的不確定

<input type="text" id = "currentPrice"> 
<button type="button" id = "calcButton">Show</button> 

var Newchart = function() { 
    this.prices = [] 
} 
Newchart.prototype.addNewprice = function() { 
    var priceValue = +(document.getElementById('currentPrice').value); 
    this.prices.push(priceValue); 
    console.log('hello') 
} 
var c = new Newchart(); 
var el = document.getElementById("calcButton"); 
el.addEventListener("click", c.addNewprice, false); 

回答

1

這是因爲背景是在window回調的呼叫,而不是你的Newchart實例。

一個解決方案是使用bind

el.addEventListener("click", c.addNewprice.bind(c), false); 

的MDN有關於這個問題的文件:The value of this within the handler

問題變量的
+0

我確定它是重複的。如果有人發現一個好的質量保證,我會關閉。 –

+0

也許https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback –

+0

@FelixKling這有點太籠統,但它會做。關閉。我讓我的回答集中在這個問題上。 –

0

this

el.addEventListener("click", c.addNewprice, false); 

編輯 - 通過@dystroy

建議你的情況this指向window不是classfunction

+0

不是'this'不是'事件'。 –

+0

@dystroy,好的,請讓我知道,究竟addEventListner被稱爲什麼? –

+0

只需閱讀我的答案 –

相關問題