0

How do you "add" an argument to a function call that you don't call directly? Specifically, I have

(function(){
        //I have the context of `that` here
        var oldLog = console.log;
        console.log = function (message) {
            //I want the context of `that` over here too
            oldLog.apply(console, arguments);
        };
})(that);

I'm trying to do this thing where i'm hijacking window's console as done in the accepted answer as shown here: Capturing javascript console.log?

Because console.log has to get called with the window.console's context (since i'm getting the log message from there), I don't have control over how it gets called and the arguments's it gets passed. How do I add that into the argument list so that I can have that whenconsole.log gets called.

TLDR; how do call a function with modified argument list but with same context.

Community
  • 1
  • 1
julianljk
  • 1,297
  • 10
  • 12

1 Answers1

0
(function(that){

    function fn(arg1, arg2){
        alert(arg1);
        alert(arg2);
    }

    function callFnWithExtraArg(arg1){

        // `arguments` is not a real array, so `push` wont work.
        // this will turn it in to an array
        var args = Array.prototype.slice.call(arguments)

        // add another argument
        args.push(that)

        // call `fn` with same context
        fn.apply(this, args)
    }

    callFnWithExtraArg('first arg')

})('arg 2');
Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52