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

戏子无情 提交于 2019-11-29 10:57:37

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.

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