我有一个函数,它是名为 server
的对象的一部分,即 server.log 是我用来记录数据的函数。尽管我希望 server.log 可用于其他文件中的函数,但我不想将服务器的其他属性传递给其他函数。
function test() {
testingThis(server.log);
}
function testingThis(logf) {
logf("test123");
}
我收到一条错误消息
Cannot read property 'emit' of undefined
我正在使用 happy 控制台模块来记录(server.log 在测试功能中工作正常)。
最佳答案
大概server.log
期望this
引用server
。但是,在调用函数的方式中,this
引用全局对象或undefined
(严格模式下)。
Bind 服务器
的函数:
testingThis(server.log.bind(server));
另请参阅How to access the correct `this` context inside a callback? .
关于javascript - 在javascript中将函数作为参数传递,未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597311/