As part of a webpage I'm building, I've been trying to put an onchange function inside of a class unsuccessfully. Am I just doing it incorrectly or is it not supposed to work? I'm still kind of new to javascript and would love an explanation for this.
I have a Product class to handle different functions with myProduct(s), and all products have dedicated inputs. Given the example I created below to update the price, why can't I just put the onchange directly in the class? It would be much handier because it is the same function for every product. Hopefully this is not a too stupid question. :)
class Product {
constructor(name,price){
this.name= name;
this.price= price;
this.in = document.getElementById(this.name);
}
updatePrice(){
this.price= this.in.value;
console.log(this.price);
}
// - Would love to put the onchange function here like
// this.in.onchange = () => this.update();
}
// My only solution so far is to make a new onchange function for each Product like:
let myProductName1 = new Product('myProductName1',200);
myProductName1.in.onchange = () => myProductName1.updatePrice();
let myProductName2 = new Product('myProductName2',300);
myProductName2.in.onchange = () => myProductName2.updatePrice();
Thanks in advance!