Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获类型错误:无法读取属性';推动';未定义的_Javascript - Fatal编程技术网

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

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 () {

在控制台中调用时,我可以将项目推送到prices数组,但在单击按钮时则不能

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