IE’s Function.apply() doesn’t like null

Well, after trying to find what the problem was with my script (it was working well in Firefox, but not in IE, sounds familiar??) I realized that Internet Explorer doesn’t like null to be passed as the second parameter to Function.apply…

According to Mozilla’s documentation, the second parameter to Function.apply should be:

An argument array for the object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function.

Since I was using apply only to bind this I decided to pass null as the second parameter… apparently IE doesn’t like that… After a bit of searching I found out that with IE, if you want to use Function.apply and not pass any parameter, you should just omit the second parameter or else IE will throw a “TypeError” if your parameter is not an array. So basically just use:

myfunction.apply(this);

Instead of:

myfunction.apply(this, null);

It will work in Mozilla since, as they mention in their doc, the second argument can be null or undefined so… all is well, and everyone is happy!…

2 Comments

  1. Posted January 31, 2010 at 9:03 pm | Permalink

    thanx a lot with the advice, i broke my head in try to catch the error…
    I have a bit harder situation cause i had to call function in the scope from another function, like:
    function somename(func, scope, args){
    func.apply(scope, args);
    }
    my code was falling and I always got message: object required…
    now my code looks like:
    function somename(func, scope, args){
    func.apply(scope, args || []);
    }
    IE happy so am I:)

  2. Posted April 13, 2010 at 4:20 pm | Permalink

    Thanks for this gem! I thought I was losing my @#$#@@ mind!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*