This and $ (this) in widgets

What does it mean and does $ (it) 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.

+3


source to share


5 answers


It mostly depends on the calling _create method ... anyway:

  • this

    refers to the "owner" of the function

  • $(this)

    is the above object wrapped in 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

+5


source


Inside the event handler of a standard style widget, jQuery this

will reference the DOM element associated with the event, $(this)

create a jQuery wrapper around this

, and the DOM element (again) available as this

.



But when your widget's functions are called, it usually this

refers to the jQuery object that function was called on, not a specific DOM element. Then you work with a consistent set of elements inside that jQuery object.

+3


source


In a jQuery integrated method:

$.fn.yourFunction = function() {
  // ...
};

      

the value this

is the jQuery object itself. So there is no reason to wrap it up with this

another jQuery call, although it doesn't hurt.

In the callback to the event handler:

$('#myButton').click(function() {
  // ...
});

      

the value this

is the target DOM element of the event, or the target if the event is fired on something other than the actual DOM.

In other jQuery callback situations, for example .each()

, the value is this

usually determined by the nature of the jQuery object.

The result of everything inside a jQuery-integrated function (first sample), you usually do not carry over this

to another jQuery call; it's already a jQuery object. In all other cases, if you want to use this

with jQuery capabilities, you need to wrap it.

+2


source


In this context, "this" is the actual JQuery widget object that allows you to query things like widgetName, widgetEventPrefix, etc., whereas "$ (this)" is just a JQuery object for "this" which you can not use the properties of the widget.

+1


source


this represents the contructor you are in. For example, in a click event, when the dom element is clicked, the function constructor will be created in the function;

function test{
    this.b = "hello jupiter";
}
var a = new test();
alert(a.b);

      

There is really nothing special about $ (this). There is a function named $ and "this" is a parameter, for example alert;

$(this);
//just like
alert("some string);

      

+1


source







All Articles