Illegal Invocation with javascript?

javascript

Solution

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/

Problem

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/

Original source