0

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!

fulvy
  • 1
  • Have you tried to attach the listener in the class constructor? – Nasa Jun 19 '20 at 13:40
  • `updatePrice` cares about the value of `this`, so you have to make sure it gets the correct value of `this`. – Quentin Jun 19 '20 at 13:41
  • Meh, it's marked as duplicate, but still, it was just enough to reference it in the constructor: https://jsfiddle.net/24qkydev/ that's it. – briosheje Jun 19 '20 at 13:42

0 Answers0