What do this and $(this) mean inside a widget method like create?
For example, Having a widget like this,
$.widget("sample.CustomWidget", {
options:{
},
_create: function(){
// Here what do this and $(this) mean
}
});
Thanks in advance,
-Raja.
What do this and $(this) mean inside a widget method like create?
For example, Having a widget like this,
$.widget("sample.CustomWidget", {
options:{
},
_create: function(){
// Here what do this and $(this) mean
}
});
Thanks in advance,
-Raja.
It basically depends on the caller of the _create method... anyway:
this
refers to the 'owner' of the Function
$(this)
is the above object wrapped into a jQuery object
see also:
http://www.quirksmode.org/js/this.html
http://www.bennadel.com/blog/1838-Wrapping-The-Window-Object-In-A-jQuery-Wrapper.htm
Within an event handler of a standard jQuery UI-style widget, this
will refer to the DOM element related to the event, $(this)
creates a jQuery wrapper around this
, and the DOM element (again) is available as this
.
But when your widget functions are called, typically this
refers to the jQuery object on which the function was called, not a specific DOM element. You then operate on the matched set of elements within that jQuery object.
In a method integrated with jQuery:
$.fn.yourFunction = function() {
// ...
};
the value of this
is the jQuery object itself. There's no reason, therefore, to wrap this
with another call to jQuery, though it doesn't hurt.
In a callback to an event handler:
$('#myButton').click(function() {
// ...
});
the value of this
is the target DOM element of the event, or the target object if the event is triggered on something other than the actual DOM.
In other jQuery callback situations, like .each()
for example, the value of this
is generally determined by the nature of the jQuery object.
The upshot of all that is that inside an integrated-with-jQuery function (first sample), you generally don't wrap this
in another call to jQuery; it's already a jQuery object. In all other cases, if you want to use this
with jQuery facilities, you do have to wrap it.
In that context, "this" is the actual JQuery widget object, which allows you to query things such as widgetName, widgetEventPrefix etc, whereas "$(this)" is just the JQuery object for "this", which you can't get the widget properties using.
this represents the contructor you are in. For example in a click event, the dom element being clicked, in a function the constructor of function;
function test{
this.b = "hello jupiter";
}
var a = new test();
alert(a.b);
Acctually there is nothing special with $(this). There is a function called $ and "this" is it's parameter, like alert;
$(this);
//just like
alert("some string);