Skip to content

Referenced call of logger.info() or logger.error() #5019

Answered by tonygermano
tom08zehn asked this question in Q&A
Discussion options

You must be logged in to vote

In pure javascript, when you invoke logger.info("foo") it is (roughly) the same as logger.info.call(logger, "foo").

When you create the reference to the function at the top level, you are no longer calling it as a property of an object, so it is roughly the same as logger.info.call(this, "foo"), where this is the global object. Since info is really a Java method, it's going to complain if you try to invoke it on the wrong type.

Using Function.prototype.bind, you can create a new function that always uses the same object for the value of this when the method is invoked.

var func;
if(1) {
	func = logger.info.bind(logger);
} else {
	func = logger.error.bind(logger);
}
func("foo")

Replies: 4 comments 8 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@tom08zehn
Comment options

@tom08zehn
Comment options

Comment options

You must be logged in to vote
4 replies
@tom08zehn
Comment options

@jonbartels
Comment options

@tom08zehn
Comment options

@odoodo
Comment options

Comment options

You must be logged in to vote
2 replies
@tom08zehn
Comment options

@tonygermano
Comment options

Answer selected by tom08zehn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants