Access to 'this' when closing Javascript

It is more a sanity test than anything else. I found that when working with closure in Javascript, I often use the following template to access the enclosing class from within the function:

MyClass.prototype.delayed_foo = function() {
    var self = this;
    setTimeout(function() {
        self.foo(); // Be nice if I could use 'this' here
    }, 1000);
};

Obviously, this works fine, and it’s not even a big problem with the job. There is only this little itch in the back of my brain that says, "You do it too hard, mannequin!" Is this a common pattern?

+5
source share
2 answers

This is a common pattern, except that it is thatoften used instead self.

+6
source

You can use the hidden binding function as follows:

var Binder = function(fnc, obj) {
    return function() {
        fnc.apply(obj, arguments);
    };
};

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

jsfiddle:

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

+4

All Articles