Accessing 'this' in Javascript closure

前端 未结 2 830
花落未央
花落未央 2021-01-19 01:58

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

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-19 02:19

    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/

提交回复
热议问题