5

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).

depperm
  • 10,606
  • 4
  • 43
  • 67
user1692342
  • 5,007
  • 11
  • 69
  • 128

1 Answers1

7

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?.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Yes you are right. Its working now :) Was this pointing to the object of testingThis function ? – user1692342 Jul 23 '15 at 20:25
  • 1
    I'm not sure how you came across this answer. The question was confusing, ill-defined, and poorly explained. I wouldn't have assumed the value/scope of `this` to be an issue here, because I did not see `this` being used at all. The one helpful piece was the emit error message. – vol7ron Jul 23 '15 at 20:28
  • 1
    @user1692342: No. As I said, inside `logf` (`server.log`) `this` would refer to the global object or `undefined`. – Felix Kling Jul 23 '15 at 21:11
  • 1
    @vol7ron: Just an educated guess from the error message + seeing that `log` looses its reference to `server` ... and my crystal ball of course! – Felix Kling Jul 23 '15 at 21:12