Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal Invocation with javascript?

Tags:

javascript

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/

like image 509
SB2055 Avatar asked Nov 26 '13 22:11

SB2055


2 Answers

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/

like image 85
Kevin B Avatar answered Oct 26 '22 22:10

Kevin B


You can try this out, using .bind

doThis(window.location.replace.bind(window.location));
like image 32
qwertynl Avatar answered Oct 26 '22 20:10

qwertynl