首页 > 解决方案 > 将类方法传递给函数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)

标签: javascriptnode.jsclassthis

解决方案


您必须将正确的上下文绑定到函数。试试这个:

callingFunc(example.getDay.bind(example));

推荐阅读