简体   繁体   中英

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 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 just fine, and it's not even a big hassle to work with. There's just this little itch in the back of my brain that says 'You're making this too complicated, dummy!' Is this the commonly accepted pattern?

这与异常的普遍接受的模式that经常使用的,而不是self

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

var Binder = function(fnc, obj) {
    return function() {
        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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM