未捕获的TypeError:this.method不是函数-Node js class export [英] Uncaught TypeError: this.method is not a function - Node js class export

查看:90
本文介绍了未捕获的TypeError:this.method不是函数-Node js class export的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是node.js的新手,并且我想要求一个类.我使用了 https://developer.mozilla.org/en/docs/Web/JavaScript/参考/类作为参考.但是,例如,当我这样做时:

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未捕获的TypeError:this.say不是函数

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

应该说app.js是electronic.js渲染器进程,并且它是使用rollup.js捆绑的.

It should be said that app.js is the electron.js renderer process and it bundled using rollup.js

为什么会这样?

更新:抱歉,我忘记在输入伪代码时添加一行.当我通过回调调用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.

这篇关于未捕获的TypeError:this.method不是函数-Node js class export的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆