简体   繁体   English

不能在函数中使用传递对象的方法

[英]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.当我现在想把它放在另一个 js 文件 Linker.js 中时,问题就出现了。 The code you see works fine if you remove the thermo.up(1) from Linker.js如果您从 Linker.js 中删除 thermo.up(1),您看到的代码可以正常工作

Linker.js链接器.js

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

Thermostat.js恒温器.js

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

Index.js索引.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)

How I fixed it was how Taplar described.我是如何修复它的,这是 Taplar 所描述的。

My class for the Thermostat had class methods, not instance methods.我的恒温器类有类方法,而不是实例方法。 Removing the static keyword for my methods fixed my problems.删除我的方法的 static 关键字解决了我的问题。

Javascript Scope strikes again. Javascript Scope 再次来袭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM