RSS

this, $(this), $this and that!

30 Aug

These terms may confuse beginners in learning jQuery.

this in a javascript function closure refers to the object invoking that function, for example:

var target = {
    getObject: function () {
        return this;
    }
};

alert(target.getObject());    // target object

Here this refer to the javascript global object which is the window property:

var getGlobalObject = function () {
    return this;
}

alert(getGlobalObject());    // window

More info on this: Understanding JavaScript’s this keyword

$(this) wraps this into a jQuery object so that we could use jQuery api with it:

jQuery.click() example below binds click event callback to all div elements on the page. this in the callback function refers to the clicked div element. Using $(this) to wrap it into a jQuery object to take advantage of jQuery.animate():

$("div").click(function () {
    $(this).animate({ "opacity": 0 });
});

$this and that are just variable names. $ is a valid character in declaring javascript variables. Any variable can do their job but it’s better to keep the naming intuitive.

$this is usually refering to $(this) for later use:

$this = $(this);

$this.animate({ "opacity": 1 });

The object which this refers to frequently changes in Javascript when scope changed by using functions. A common use of that is to refer to the original object. Especially useful when developing plugin or widget.

Here is a simple click event to fade out all div elements and alert the number of them:
(It’s only for demonstration, declaring properties like this is not recommended.)

$("#hide-link").click(function () {
    this.hideElementCount = 0;
    var that = this;

    $("div").each(function () {
        $(this).animate({ "opacity": 0 }, 2000);
        that.hideElementCount++;
    });

    alert(this.hideElementCount);
});

References:
What is the reason for var $this = this
What is the difference between “this”, “$this” and “$(this)”?
$this vs $(this) in jQuery

About these ads
 
Leave a comment

Posted by on August 30, 2012 in Javascript, jQuery

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 364 other followers

%d bloggers like this: