Maintaining the reference to “this” in Javascript when using callbacks and closures

后端 未结 3 477
春和景丽
春和景丽 2020-11-30 20:16

I find myself assigning \"this\" to a variable so I can easily use it in callbacks and closures.

Is this bad practice? Is there a better way of referring back to the

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 21:03

    You could create a proxy for the callback with:

    var createProxy = function(fn, scope) {
      return function () {
        return fn.apply(scope, arguments);
      }; 
    };
    

    Using this, you could do the following:

    db.User.findById('ABCD', createProxy(function(err, user)) {
      this.foo(user);
    }, this));
    

    jQuery does something similar with: $.proxy

    And, as others have noted using bind, have a look here if compatibility is an issue:

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Compatibility

提交回复
热议问题