Javascript Scope: Function.apply is your friend

Once you get past the basics of Javascript managing the “this” keyword becomes more and more complex. For me, when writing object-oriented js, I often find it frustrating that methods are loosly bound to their objects. So If I pass a function pointer to somewhere else it is impossible to determine what object that pointer belonged to, because “this” might refer to a different scope.

I hacked together a very ugly solution to this problem:

    function scopeChange(func, obj){
        obj.temp = func;
        return function(){
            obj.temp(arguments[0], arguments[1], arguments[2];
        };
    };

Now, this is a crappy solution, because it breaks with too many arguments and it also creates a pretty ugly closure. Now, luckily I ran this by some people, and it turns out there is a much better way to do this, the “apply” method of the function prototype in javascript allows you to execute a function in the scope of a passed object. So the new “scopeChange” funciton will look like this:

    function scopeChange(func, obj){
        return function(){
            func.apply(obj, arguments);
        };
    };

Much nicer! Now how did I get this far in life without knowing about function.apply?