I have a function:
var doThis = function(callback){
callback('google.com');
}
If I do this, it works:
doThis(alert);
But if I do this, I get an error:
doThis(window.location.replace);
Uncaught TypeError: Illegal invocation
I'm building a wrapper for AJAX calls and I need to support functions like alert
, custom functions, as well as window.location.replace
. What am I doing wrong?
Fiddle: http://jsfiddle.net/32LJf/1/
When you store a function in a different context than it was intended, it will no longer have access to the properties it had access to previously. For example:
var myObj = {
foo: "foo",
alert: function(){
alert(this.foo);
}
}
myObj.alert(); // "foo"
var a = myObj.alert;
a(); // undefined.
when executing the alert function as a property of myObj, it has access to this.foo, however, when you store that function somewhere else, it no longer has access to it. to solve it, store an anonymous function that executes the function instead.
var myObj = {
foo: "foo",
alert: function(){
alert(this.foo);
}
}
myObj.alert(); // "foo"
var a = function(){myObj.alert();}
a(); // "foo".
and applied to your code:
doThis(function(){window.location.replace();});
http://jsfiddle.net/rhdZa/1/
You can try this out, using .bind
doThis(window.location.replace.bind(window.location));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With