News for hackers. Stuff that matters.
Re: by richcollins on Monday March 07, 2011 @12:20AM (#2296124)
Don't do it. Do this instead:

var self = this; function(){ self.foo() }

Re: by jonursenbach on Monday March 07, 2011 @12:21AM (#2296127)
This.

heh.

Re: by DCoder on Monday March 07, 2011 @12:40AM (#2296172)
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/ .

Re: by joske2 on Monday March 07, 2011 @12:48AM (#2296193)
In ES5 you have Function.prototype.bind that returns a new function with this bound to whatever you want. You can also pass extra default arguments. On older browsers you could use es5-shim for this functionality.

See https://developer.mozilla.org/en/JavaScript/Reference/Global...

Re: by sisk on Sunday March 06, 2011 @11:47PM (#2296064)
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.
Re: by thomasdavis on Sunday March 06, 2011 @11:58PM (#2296089)
I have used this method many times before also, added it as an alternative implementation on the site.
Re: by joetyson on Monday March 07, 2011 @12:35AM (#2296160)
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);
Re: by travisglines on Sunday March 06, 2011 @11:43PM (#2296051)
Solid example, I frequently find myself saying something to the effect of:

    var this_autobot = this;
    async_function = function(){
      this_autobot.fire();
    }
Re: by joshd on Sunday March 06, 2011 @11:48PM (#2296070)
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();
    }
Re: by Johngibb on Monday March 07, 2011 @12:15AM (#2296115)
I've used $this before
Re: by ronnier on Monday March 07, 2011 @12:08AM (#2296104)
Is "for noobs" really necessary?