Reputation: 18891
I'm trying to write a wrapper for console.log
.
I found the .apply
function in Function prototype, but it's giving me errors:
function _log() {
if (opts.debug) console.log.apply(this, arguments);
}
opts.debug
is a key in my config array.
Error:
Uncaught TypeError: Illegal invocation at :2:13 at Object.InjectedScript._evaluateOn (:905:140) at Object.InjectedScript._evaluateAndWrap (:838:34) at Object.InjectedScript.evaluate (:694:21)
What's wrong with the way I'm trying to do it? And, how to do it right? Thanks.
Upvotes: 0
Views: 153
Reputation: 21779
You are invoking the console.log
method in an invalid scope, in order to make it work, you have to invoke it in the console
's scope:
function _log() {
if (opts.debug) console.log.apply(console, arguments);
}
After testing it a couple of times and it seems that @Rob M. is right about his comment. The binding has to be done with the console
scope.
Upvotes: 2
Reputation: 665354
console.log
expects to be called as a method of console
, i.e with console
for the receiver (this
argument, first parameter to apply
). Currently you're passing this
to apply
, whatever this is (possibly the global object), it's not the console
object. Use
function _log() {
if (opts.debug) console.log.apply(console, arguments);
// ^^^^^^^
}
Upvotes: 3