具体的なパラメーターを使用して 2 番目の関数を実行するラムダ関数を作成しています。このコードは Firefox では機能しますが、Chrome では機能しませんUncaught TypeError: Illegal invocation
。私のコードの何が問題なのですか?
var make = function(callback,params){
callback(params);
}
make(console.log,'it will be accepted!');
具体的なパラメーターを使用して 2 番目の関数を実行するラムダ関数を作成しています。このコードは Firefox では機能しますが、Chrome では機能しませんUncaught TypeError: Illegal invocation
。私のコードの何が問題なのですか?
var make = function(callback,params){
callback(params);
}
make(console.log,'it will be accepted!');
コンソールのログ機能は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!');
「this」を必要とする関数を新しいラムダ関数にラップし、それをコールバック関数に使用できます。
function make(callback, params) {
callback(params);
}
make(function(str){ console.log(str); }, 'it will be accepted!');