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", {
_create: function(){
// Here what do this and $(this) mean


Thanks in advance,



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:



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.



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.



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.



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();


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

//just like
alert("some string);




All Articles