Referenced call of logger.info() or logger.error() #5019
-
Best description for my request is a code snippet: // Depending on a condition I want to call either logger.info() or logger.error()
// ... so I store a reference to that function in variable `func` as follows:
var func;
if(1) {
func = logger.info;
} else {
func = logger.error;
}
logger.debug("func: " + func); Prints:
Looks great! Now call it: func("foo"); Fails with error: How to solve that?Full error:
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 8 replies
-
P.S. The following answer is not accepted 😅 if(1) {
logger.info("foo");
} else {
logger.error("foo");
} The background of my request is more complex and the code snippet just illustrates the basic issue. |
Beta Was this translation helpful? Give feedback.
-
I'm not sure of the answer but this information might help. The logger is added to the JS scope here Does this information help you? What is your use case? Do you just want a universal toggle between logging at the info level and the error level? |
Beta Was this translation helpful? Give feedback.
-
Updated (and this time tested) proposal: var func;
if(1) {
func = function(something){logger.info(something)};
} else {
func = function(something){logger.error(something)};
}
// first parameter is the context
func.call(this, 'I am some log message'); Further details about call() can be found here. |
Beta Was this translation helpful? Give feedback.
-
In pure javascript, when you invoke 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 Using Function.prototype.bind, you can create a new function that always uses the same object for the value of var func;
if(1) {
func = logger.info.bind(logger);
} else {
func = logger.error.bind(logger);
}
func("foo") |
Beta Was this translation helpful? Give feedback.
In pure javascript, when you invoke
logger.info("foo")
it is (roughly) the same aslogger.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")
, wherethis
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.