6

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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Yes you are right. Its working now :) Was this pointing to the object of testingThis function ?
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.
@user1692342: No. As I said, inside logf (server.log) this would refer to the global object or undefined.
@vol7ron: Just an educated guess from the error message + seeing that log looses its reference to server ... and my crystal ball of course!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.