Javascript 未捕获类型错误:无法读取属性';推动';未定义的
在控制台中调用时,我可以将项目推送到prices数组,但在单击按钮时则不能Javascript 未捕获类型错误:无法读取属性';推动';未定义的,javascript,Javascript,在控制台中调用时,我可以将项目推送到prices数组,但在单击按钮时则不能 <input type="text" id = "currentPrice"> <button type="button" id = "calcButton">Show</button> var Newchart = function () { this.prices = [] } Newchart.prototype.addNewprice = function () {
<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);
显示
var Newchart=函数(){
这是价格=[]
}
Newchart.prototype.addNewprice=函数(){
var priceValue=+(document.getElementById('currentPrice').value);
这个.价格.推送(priceValue);
console.log('hello')
}
var c=新的Newchart();
var el=document.getElementById(“calcButton”);
el.addEventListener(“单击”,c.addNewprice,false);
这是因为上下文是回调调用中的窗口
,而不是您的Newchart
实例
解决方案是使用:
MDN有关于此问题的文档:.此变量的问题
el.addEventListener("click", c.addNewprice, false);
编辑-由@dystroy建议
在您的情况下,
此
指向的是窗口
而不是类
或函数
我确信它是重复的。如果有人找到一个好的QA,我会关闭。也许@FelixKling有点太笼统了,但也可以。关闭我让我的答案集中在这个问题上。不,这个
不是事件
@dystroy,好的,那么请让我知道,addEventListner到底叫什么?只需阅读我的答案
el.addEventListener("click", c.addNewprice, false);