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.
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)
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.
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.
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 }
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();
});
};
That looks like your best option, I don't think there's a better way. (someone correct my if I'm wrong).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With