38

具体的なパラメーターを使用して 2 番目の関数を実行するラムダ関数を作成しています。このコードは Firefox では機能しますが、Chrome では機能しませんUncaught TypeError: Illegal invocation。私のコードの何が問題なのですか?

var make = function(callback,params){
    callback(params);
}

make(console.log,'it will be accepted!');
4

2 に答える 2

66

コンソールのログ機能はthis、(内部的に) コンソールを参照することを想定しています。問題を再現する次のコードを検討してください。

var x = {};
x.func = function(){
    if(this !== x){
        throw new TypeError('Illegal invocation');
    }
    console.log('Hi!');
};
// Works!
x.func();

var y = x.func;

// Throws error
y();

make 関数にバインドthisされるため、動作する (ばかげた) 例を次に示します。console

var make = function(callback,params){
    callback.call(console, params);
}

make(console.log,'it will be accepted!');

これも機能します

var make = function(callback,params){
    callback(params);
}

make(console.log.bind(console),'it will be accepted!');
于 2012-01-18T03:36:22.743 に答える
4

「this」を必要とする関数を新しいラムダ関数にラップし、それをコールバック関数に使用できます。

function make(callback, params) {
  callback(params);
}

make(function(str){ console.log(str); }, 'it will be accepted!');
于 2012-01-18T07:21:57.047 に答える