2016-08-09 25 views
0

直接呼び出さない関数呼び出しに引数をどのように "追加"しますか? 具体的には、私はここに示したように、私は受け入れ答えに行ったように私はwindowのコンソールをハイジャックしています。このことをやろうとしている関数呼び出しに余分な引数を追加する方法

(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); 

がありますと呼ばれる取得する必要がありCapturing javascript console.log?

console.logのでwindow.consoleのコンテキスト(そこからログメッセージを取得しているので)では、どのように呼び出され、引数が渡されるかを制御できません。どのようにthatを引数リストに追加すると、console.logが呼び出されたときにthatを持つことができます。

TLDR;引数リストが変更されたが同じコンテキストで関数を呼び出す方法

答えて

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'); 
関連する問題