-3

i can push an item to prices array when invoked in console but not when i click the button..

<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);
kam
  • 425
  • 2
  • 6
  • 24

2 Answers2

1

That's because the context is window in the callback's call, not your Newchart instance.

A solution is to use bind :

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

The MDN has a documentation regarding this problem : The value of this within the handler.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

issue of this variable

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

Edit - suggested by @dystroy

In your case this points to the window not the class or the function.

Harpreet Singh
  • 2,651
  • 21
  • 31