在javascript中传递函数作为参数,未定义错误

时间:2015-07-23 20:21:23

标签: javascript node.js

我有一个函数,它是一个名为server的对象的一部分,即server.log是我用来记录数据的函数。服务器的其他属性我不想传递给其他函数,但我希望server.log可用于其他文件中的函数。

function test() {
    testingThis(server.log);
}

function testingThis(logf) {
    logf("test123");
}

我收到错误说

  

无法读取属性' emit'未定义的

我使用快乐的控制台模块进行日志记录(server.log在测试功能中工作正常)。

1 个答案:

答案 0 :(得分:1)

大概server.log期望this引用server。但是,调用函数的方式this引用全局对象或undefined(在严格模式下)。

Bind server的功能:

testingThis(server.log.bind(server));

另见How to access the correct `this` context inside a callback?