Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I keep the context of 'this' in jquery

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.

like image 409
disc0dancer Avatar asked Jun 25 '09 12:06

disc0dancer


People also ask

What is '$' in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

What is jQuery context?

The context property contains the original context passed to jQuery, which could be a DOM node context, or, if no node is passed, the document context.

How to use context in JavaScript function?

In JavaScript, “context” refers to an object. Within an object, the keyword “this” refers to that object (i.e. “self”), and provides an interface to the properties and methods that are members of that object. When a function is executed, the keyword “this” refers to the object that the function is executed in.

What is context in Ajax?

All the context does is it sets the value of this in the callbacks. So if you're in an event handler, and you want this in the callbacks to be the element that received the event, you'd do: context:this, success:function() { // "this" is whatever the value was where this ajax call was made }


2 Answers

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();
  });
};
like image 141
Patrick McElhaney Avatar answered Sep 22 '22 23:09

Patrick McElhaney


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

like image 44
karim79 Avatar answered Sep 23 '22 23:09

karim79