javascript - 将类方法传递给函数nodejs
问题描述
我是 nodejs 的新手,我尝试编写一个函数,将函数/方法作为参数并从内部调用该函数/方法。
例如:
function add(a, b) {
return a + b;
}
function callingFunc(func) {
return func(1, 2);
}
callingFunc(add);
但问题是当我尝试从调用函数调用实例的方法时。
class Example {
constructor(day) {
this.day = day;
}
getDay() {
return this.day
}
}
function add(a, b) {
return a + b;
}
function callingFunc(func) {
return func(1, 2);
}
const example = new Example("sunday");
callingFunc(example.getDay);
它返回此错误:
/home/cg/root/8845458/main.js:9
return this.day
^
TypeError: Cannot read property 'day' of undefined
at getDay (/home/cg/root/8845458/main.js:9:20)
at callingFunc (/home/cg/root/8845458/main.js:18:12)
at Object.<anonymous> (/home/cg/root/8845458/main.js:22:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
解决方案
您必须将正确的上下文绑定到函数。试试这个:
callingFunc(example.getDay.bind(example));
推荐阅读
- wordpress - 当我有 2 个具有自动缩放功能的 aws 实例时,如何从单个位置更改 wordpress 数据和文件
- c# - 使用 C# Winform 登录网站 - 没有 id
- android - 如何从终端运行 Android 虚拟设备管理器
- delphi - 使用 Delphi 将字符串传递给 oleobject
- php - 对PHP文件角度的http请求出错
- facebook - 如何避免数百万用户的 Facebook Graph API 限制
- java - 如何在导航抽屉菜单中使用彩色图标?
- java - 将 DatePicker 中的数据添加到 DB Javafx
- c# - 我无法在浏览器上第二次玩浏览器游戏!C# WPF/WinForm
- delphi - 如何防止最小化应用程序最小化所有表单?