問題描述
我是 node.js 的新手,我正在嘗試要求一個類.我用過 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes 作為參考.但是,例如,當我這樣做時:
I am new to node.js and I am trying to require a class. I have used https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes 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.
這篇關于未捕獲的類型錯誤:this.method 不是函數 - 節點 js 類導出的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!