Share Tweet Reccomend

jQuery: What’s the Difference Between $(this), $this, and this?

When doing jQuery development and looking at the code in other people’s jQuery functions and plugins you’ll eventually see that different developers will use different syntaxes in different places. This is probably most apparent in the use of the term “this”. Sometimes you will see this. Other times you will see $(this) and still other times you will see $this. What is the difference between all of these and when should you use each one?

The this pointer in JavaScript refers to the current object that we are running our code inside. In JavaScript everything is an object, so the scope of this is always changing.

Let’s say we had a page like one that is shown below…

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<div id="one" class="myClass">One</div>
<div id="two" class="myClass">Two</div>
<div id="three" class="myClass">Three</div>
<div id="four" class="otherClass">Four</div>
<script type="text/javascript">
</script>
</body>
</html> 

Now in the <script> section let’s add some jQuery to loop through all of the elements with the “myClass” class (all the <div>’s on the page. As many know, to do this we use the jQuery each method. Inside of each we can use the pointer “this” to refer to the current DOM element in set of elements we are on.

$(document).ready(function() {
    $('.myClass').each(function(){
       // do something with this here
    });
});

Let’s use the native JavaScript function getAttribute() to get the id attribute of each element.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log(this.getAttribute('id'));
    });
});

If we look in our console, we can see that the text one, two, three appears (the id attributes of each DOM element that has “myClass”). So everything works as expected.

But as you know jQuery also has a method for getting an attribute: the attr() method. So let’s try it with that.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log(this.attr('id'));
    });
});

However if we look in our console we get an error.

Uncaught TypeError: Object # has no method ‘attr’.

Why is that? We know we are referencing the correct DOM element. Well, it’s because we haven’t wrapped this (the current DOM element) in jQuery so that we can call jQuery methods on it. That’s really the big distinction between $(this) and this. They both refer to the same object. However, if you want to use any jQuery on the object, it must be wrapped in a jQuery object as $(this) like so.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log($(this).attr('id'));
    });
});

The reverse is also true. Because the $() is a jQuery wrapper, you cannot call native JavaScript on it. So $(this).getArribute(‘id’) also wouldn’t work.

So that’s the big thing to remember. If you want to call a jQuery method on your object, wrap it it $(). If you want to use a native JavaScript method, don’t wrap it in $(). Just use plain ol’ this

What about $this?

$this is a little different because it’s actually just a variable that uses the $. It has no inherent relation to jQuery. It would be no different than JavaScript variables named $corn or $carrots. You just was easily say var $this = “My pet cat is named Mittens.”; It’s just a variable with the dollar sign in it. JavaScript allows characters like this in variable names. The reason that you see use of $this inside of jQuery plugins is that often times developers in the global scope inside of their plugin will say something like:

var $this = $(this);

That way they can always have a reference to the object on which the plugin was called. The scope of “this” will change in any methods used inside the plugin so it’s always good to have a global variable (that is, global inside the plugin scope) which you can refer to the object on which the plugin was called. But the important thing to remember is that $this has no inherent relation to jQuery. It’s just a variable like any other.

Personally however, I never really liked naming the DOM element object using that convention. I always used var object = $(this); as can be seen in some jQuery plugins I have written. I figured with all the this’s running around inside of all of these objects, no need to throw another one in there if not absolutely necessary. But it’s really just a matter of personal preference there :)

Hopefully this has cleared up some of the weirdness in uses of different this syntaxes.

Share Tweet Reccomend

JavaScript Inheritance

Inheritance in JavaScript is an interesting and important topic. But it can sometimes be a bit tricky to grasp because JavaScript is quite a bit different from class-based languages like C++ and Java. In what follows, we’ll look at how to do inheritance in JavaScript and some things to watch out for. Before you dive into this you should have a decent understanding of the basics of JavaScript and JavaScript objects. W3 Schools has a really good quick introductory overview of JavaScript (complete with examples and exercises that you can try yourself) that can be found here.

There are many different ways to create objects in JavaScript because, well, pretty much everything is an object. However, for our purposes here when we’re discussing objects we mean the generic “Object” in JavaScript, the dynamic type that we can throw any data that we want into in a collection of key-value pairs. And taking it a step further, when we say generic “Object” what we’re really talking mostly are functions and object literals. These will be the center of our focus when discussing inheritance in JavaScript.

An empty generic “Object” object can be created in JavaScript by doing the following…

var animal = new Object();

But objects are often initialized with data. This can be done using the Object literal approach as shown below…

var Animal = {
    color: "brown",
    size: "medium"
    age: 1,
    sound: function() {
        console.log('Grunt');
    }
    move: function() {
        console.log('Running');
    }
}

We can accomplish the same thing that we did above by creating a function and then assigning properties to the function…

function Animal() {
    this.color = "brown",
    this.size = "medium"
    this.age = 1,
    this.sound = function() {
        console.log('Grunt');
    }
    this.move = function() {
        console.log('Running');
    }
}

NOTE: The function and the object literal are actually not *exactly* the same. There *are* some differences between function Animal() { } and var Animal = function() { }; mainly having to do with how and when JavaScript executes these functions at runtime. You can, for example, call function Animal() elsewhere in your code before you declare the function, but you cannot call var Animal = function() { } before you declare it. You will get an error. It’s treated as the same situation as trying to use a variable before defining it. This is due to something called “hoisting” which I recommend doing a search for if you are interested in the technical side of it.

The benefit of using a function is that we can create a new instance of different Animals if we want.

var dog = new Animal();
var cat = new Animal();
console.log(dog.size);
console.log(cat.size);

There’s a problem with this though. All the animals that we create all have the same size, color, age, etc. We’re going to want our animals to all contain different types of data. To do that, we can slightly modify our function such that we pass arguments into the constructor.

function Animal(color, size, age, sound, move) {
    this.color = color,
    this.size = size
    this.age = age,
    this.sound = function() {
        console.log(sound);
    }
    this.move = function() {
        console.log(move);
    }
}

Read More »

Share Tweet Reccomend

JavaScript Events

Events are where all the magic happens in JavaScript. Whatever context you are working within (be it a browser window or on the system/server level using Node.js), it’s pretty safe to say that a lot of “stuff” is constantly happening… clicks, loads, mouseovers, AJAX requests and responses — these are the types of things your website or application will need to respond to. In this section we will take a look at how we can use events in JavaScript…

Adding Events in the DOM

Like with many things in software, there are many different ways to do things. In the past you may have often seen stuff like the following…

<script type="text/javascript">
function showMessage(){
   alert("Hello world!");
}
</script>
<input type="button" id="messageButton" value="Submit" onclick="showMessage()" />

Here we are adding an event to this button by calling a function in the onclick attribute. This code will work fine in all modern browsers (and even really really old browsers). However this is not exactly the best approach because it intermixes application/business logic (JavaScript) with our view (HTML). A better approach is to pull this code out of the view…

var b = document.getElementById("messageButton");
b.onclick = function(){
    alert("Hello World");
};
<input type="button" id="messageButton" value="Submit" />

Here we have created a separation of concern and our button is free from having business logic intermixed within it.

Read More »