问题描述
我是 node.js 的新手,我正在尝试要求一个类.我用过 http://www.51sjk.com/Upload/Articles/1/0/335/335900_20221102095200079.jpg 作为参考.但是,例如,当我这样做时:
I am new to node.js and I am trying to require a class. I have used http://www.51sjk.com/Upload/Articles/1/0/335/335900_20221102095200079.jpg as reference. However, when I do this for example:
// talker.js class Talker { talk(msg) { console.log(this.say(msg)) var t = setTimeout(this.talk, 5000, 'hello again'); } say(msg) { return msg } } export default Talker // app.js import Talker from './taker.js' const talker = new Talker() talker.talk('hello')
我明白了:
talker.js:4 Uncaught TypeError: this.say 不是函数
talker.js:4 Uncaught TypeError: this.say is not a function
应该说app.js是electron.js的渲染进程,使用rollup.js捆绑
It should be said that app.js is the electron.js renderer process and it bundled using rollup.js
任何想法为什么会这样?
Any ideas why this would be?
更新:抱歉,我在输入伪代码时忘记添加一行.当我用回调调用 setTimeout 时,它实际上会发生.我已经更新了代码.
Update: Sorry, I forgot to add in a line when putting in the psuedo code. It actually happens when I call setTimeout with callback. I have updated the code.
推荐答案
你正在失去 this 对你的方法的绑定.
You are losing the bind of this to your method.
从此改变:
setTimeout(this.talk, 5000, 'hello again');
到这里:
setTimeout(this.talk.bind(this), 5000, 'hello again');
<小时>
当您将 this.talk 作为函数参数传递时,它接受 this 并查找方法 talk 并传递对该方法的引用功能.但是,它只传递对该函数的引用.与您在 this 中的对象不再有任何关联..bind() 允许您将引用传递给一个小存根函数,该函数将跟踪 this 并将您的方法称为 this.say(),而不仅仅是 say().
When you pass this.talk as a function argument, it takes this and looks up the method talk and passes a reference to that function. But, it only passes a reference to that function. There is no longer any association with the object you had in this. .bind() allows you to pass a reference to a tiny stub function that will keep track of this and call your method as this.say(), not just as say().
如果你这样做,你会看到同样的事情:
You can see the same thing if you just did this:
const talker = new Talker();' const fn = talker.say; fn();
这会产生同样的问题,因为将方法分配给 fn 根本不会与 talker 关联.它只是一个函数引用,与对象没有任何关联.事实上:
This would generate the same issue because assigning the method to fn takes no associate to talker with it at all. It's just a function reference without any association with an object. In fact:
talker.say === Talker.prototype.say
.bind() 所做的是创建一个小的存根函数,该函数将保存对象值,然后使用该对象调用您的方法.
What .bind() does is create a small stub function that will save the object value and will then call your method using that object.