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

CUGreen picture CUGreen · Feb 15, 2017 · Viewed 11.8k times · Source

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.

Answer

jfriend00 picture jfriend00 · Feb 15, 2017

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.