node.js - Passing a function as parameter in javascript, undefined error - Stack Overflow

I have a function which is part of an object called server, i.e server.log is a function which I use to

I have a function which is part of an object called server, i.e server.log is a function which I use to log data. There are other properties of server which I do not want to pass to other functions, though I want server.log to be available to functions in other files.

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

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

I get an error saying

Cannot read property 'emit' of undefined

I am using happy console module to log (server.log works fine in test function).

I have a function which is part of an object called server, i.e server.log is a function which I use to log data. There are other properties of server which I do not want to pass to other functions, though I want server.log to be available to functions in other files.

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

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

I get an error saying

Cannot read property 'emit' of undefined

I am using happy console module to log (server.log works fine in test function).

Share Improve this question edited Jul 23, 2015 at 20:23 depperm 10.8k4 gold badges46 silver badges68 bronze badges asked Jul 23, 2015 at 20:21 user1692342user1692342 5,24713 gold badges79 silver badges138 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Presumably server.log expects this to refer to server. However, the way you call the function, this refers to the global object or undefined (in strict mode).

Bind the function to server:

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

See also How to access the correct `this` context inside a callback?.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744268875a4566000.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信