Uncaught TypeError: this.method is not a function - Node js class export [duplicate]

纵饮孤独 提交于 2019-11-26 23:29:43

问题


This question already has an answer here:

  • How to access the correct `this` inside a callback? 10 answers

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')

I get:

talker.js:4 Uncaught TypeError: this.say is not a function

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?

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.


回答1:


You are losing the bind of this to your method.

Change from this:

setTimeout(this.talk, 5000, 'hello again');

to this:

setTimeout(this.talk.bind(this), 5000, 'hello again');

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();

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

What .bind() does is create a small stub function that will save the object value and will then call your method using that object.



来源:https://stackoverflow.com/questions/42238984/uncaught-typeerror-this-method-is-not-a-function-node-js-class-export

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!