12 comments

[ 2.9 ms ] story [ 34.9 ms ] thread
Solid example, I frequently find myself saying something to the effect of:

    var this_autobot = this;
    async_function = function(){
      this_autobot.fire();
    }
I usually use `that`. I've seen examples use `self`, but that could potentially conflict with `window.self` in the browser.

    var that = this;
    return function(){
      that.fire();
    }
(comment deleted)
I do the following a lot (setTimeout as a relevant example):

  setTimeout(
    (function(scope){
      return function(){scope.fire();};
    })(this), 500
  );
The short explanation is you return a function from an immediately-executing anonymous function that takes the current scope as a parameter.
I have used this method many times before also, added it as an alternative implementation on the site.
Is "for noobs" really necessary?
You can also create a 'bind' that returns a function that when called applies the context you desire.

  function bind(fn, selfObj) {
     return function() {
        return fn.apply(selfObj || window);
     };
  }

  callback = bind(function(){ alert(this.hello); }, this);
I don't think you're doing this right. The first .then receives a function, but the second .then executes function.apply at construction time and receives only its result (null) as the callback.

Also, after understanding what's going on, existing solutions might be better than rolling your own: http://api.jquery.com/jQuery.proxy/ .