views:

144

answers:

5

I have something like this:

var Something = function(){
  this.render = function(){};
  $(window).resize(function(){
    this.render();
  });
}

The trouble is that inside the anonymous function 'this' refers to the window object. I know I could do something like:

var Something = function(){
  this.render = function(){};
  var tempThis = this;
  $(window).resize(function(){
    tempThis.render();
  });
}

but is there a better way? This doesn't look very elegant.

+2  A: 

That looks like your best option, I don't think there's a better way. (someone correct my if I'm wrong).

karim79
+1 seconded .
Here Be Wolves
A: 

I've been doing it this way in many tight situations. It doesn't look elegant, but it never fails. Actually thats javascript closures in action.

jrh

Here Be Wolves
+10  A: 

The solution you found is the the one most people use. The common convention is to call your tempThis variable "that."

var Something = function(){
  this.render = function(){};
  var that = this;
  $(window).resize(function(){
    that.render();
  });
};
Patrick McElhaney
+1 for that (:
peirix
well having a convention makes it look more elegant :) I like "that".
Discodancer
+1 for that = this -> This is the most elegant method that I ever found for this question.
Nordin
Props to Douglas Crockford for popularizing -- if not inventing -- that convention. :-) http://javascript.crockford.com/private.html
Patrick McElhaney
Please add a "var" before "that" in order to not polute the global scope with your variable. Another convention is to call this variable "self".
Vincent Robert
I used to use "self" until I noticed that there's a global variable named "self" in browsers sometimes that refers to the global object. If you typo something, your this becomes the global object again, and no error is thrown, and it's harder to track down because it *looks* like you did the right thing, but it's doing the wrong thing anyway!
Breton
+1  A: 

FYI the ability to control this is coming in the next version of JQuery

redsquare
A: 

That's exactly what I do. It's not specific to jQuery, either.

var Construct = function() {
    var self = this; //preserve scope

    this.materials = 2000;

    this.build = function(){
        self.materials -= 100;
    };
};

Remember to use the var keyword in front of your new scope variable. Otherwise, you're creating a new global variable. As a local variable, it will still be accessible inside the inner function via a closure.

EndangeredMassa