Search code examples
javascriptfunctionclassinnerhtml

How to assign class to innerHTML?


I have a form and I want to print result when I click on the button. I know how to assign to innerHTML a result of basic function but what if I have a class?

I have something like this:


    Weight: <input type="number" id="weight" /><br/> Height: <input type="number" id="height" /><br/>

    <button type="button" id="submit">Submit</button>

    <span id="result"></span>


    class SomeClass {
        constructor() {
            this.number = 0;
            this.weight = document.getElementById('weight').value;
            this.height = document.getElementById('height').value;
        }

        FirstMethod() {
            if (this.weight < 10) {
                this.number += 1;
                return this.number;
            }
        }

        SecondMethod() {
            if (this.height < 10) {
                this.number += 2;
                return this.number;
            }
        }
    }

and on the top:


    document.getElementById('submit').addEventListener('click', result);

    function result() {
        let overall = new SomeClass().FirstMethod().SecondMethod().number;
        document.getElementById('result').innerHTML = overall;
    } 

I get an error "Uncaught TypeError: (intermediate value).FirstMethod(...).SecondMethod is not a function". I tried to do it in many different ways and nothing works.


Solution

  • You can not chain the call of new. You need to store it as an instance in a variable first.

     function result() {
            let overall = new SomeClass();
            overall = overall.FirstMethod().SecondMethod().number;
            document.getElementById('result').innerHTML = overall;
        } 
    

    But better practice is make it immutable like this:

     function result() {
            let overallInstance = new SomeClass();
            let overall = overallInstance.FirstMethod().SecondMethod().number;
            document.getElementById('result').innerHTML = overall;
        } 
    

    Also I notice, you return a value in FirstMethod(). This must return the instance itself to allow chainable calls.