Skip to content Skip to sidebar Skip to footer

Accessing 'this' In Javascript Closure

This is more of a sanity check than anything else. I've found that when working with closures in Javascript I often use the following pattern to access the enclosing class from wit

Solution 1:

This is the commonly accepted pattern with the exception that that is often used instead of self.

Solution 2:

You can pull a sneaky using a binding function like this:

varBinder = function(fnc, obj) {
    returnfunction() {
        fnc.apply(obj, arguments);
    };
};

and then changing your call to

MyClass.prototype.delayed_foo = function() {
    setTimeout(Binder(function(){
        this.foo("Lols");
    },this), 1000);
};

jsfiddle example:

http://jsfiddle.net/ctrlfrk/6VaV6/

Post a Comment for "Accessing 'this' In Javascript Closure"