我有一个函数,它是一个名为server
的对象的一部分,即server.log是我用来记录数据的函数。服务器的其他属性我不想传递给其他函数,但我希望server.log可用于其他文件中的函数。
function test() {
testingThis(server.log);
}
function testingThis(logf) {
logf("test123");
}
我收到错误说
无法读取属性' emit'未定义的
我使用快乐的控制台模块进行日志记录(server.log在测试功能中工作正常)。
答案 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?。