Search code examples
javascriptfunctionclassparametersexternal

Can't use method of passed object in function


What I have tried

I have a thermostat program, that works perfectly fine, due to it being made with test driven development. I then wrote some code in my index's area, to link my elements and buttons to the thermostat program, which all worked.

What creates the problem

The problem arises when I now want to put this in another js file, Linker.js. The code you see works fine if you remove the thermo.up(1) from Linker.js

Linker.js

function returnTemp(thermo) {
    thermo.up(1)
    console.log(thermo.temp)
}

Thermostat.js

static up(num) {
        this._tempChange(num);
        console.log(this.temp);
    };

Index.js

<!-- JS -->
<script src="src/Thermostat.js"></script>
<script src="src/Linker.js"></script>
<script>
    var stat = new Thermostat
</script>

Console

returnTemp(stat)
Uncaught TypeError: thermo.up is not a function
    at returnTemp (Linker.js:59)
    at <anonymous>:1:1
(edited)

Solution

  • How I fixed it was how Taplar described.

    My class for the Thermostat had class methods, not instance methods. Removing the static keyword for my methods fixed my problems.

    Javascript Scope strikes again.