[Programming] Understanding the "this" keyword in JavaScript
My colleague asked me how to know what the "this" keyword refers to in JavaScript. It's a bit different from other languages.
First, the rule: When you invoke a function on an object, "this" refers to the object. When you invoke a function by itself, "this" refers to the global object (the window object).
Now for some examples.
Creating an object in JavaScript is easy:
Let's add a function to this object:
When we call food.getCalories(), "this" is the food object, because we are invoking the function on the food object.
But check this out:
Here we invoke the function by itself, i.e., not on an object. "this" is the global object (i.e. window), because we are invoking the function by itself.
Now look at this:
Here we've created an automobile object, and added our function to it. "this" is the automobile object, because we are invoking the function on the automobile object.
Thus, "this" is a dynamic quantity – it is not cast in stone when the function is defined, but refers to the current object that the function is being invoked on.
First, the rule: When you invoke a function on an object, "this" refers to the object. When you invoke a function by itself, "this" refers to the global object (the window object).
Now for some examples.
Creating an object in JavaScript is easy:
var food = {};
Let's add a function to this object:
var food = {
getCalories: function() { alert(this); return 300; }
};
food.getCalories();
When we call food.getCalories(), "this" is the food object, because we are invoking the function on the food object.
But check this out:
var getCals = food.getCalories;
getCals();
Here we invoke the function by itself, i.e., not on an object. "this" is the global object (i.e. window), because we are invoking the function by itself.
Now look at this:
var automobile = {};
automobile.getCalories = getCals;
automobile.getCalories();
Here we've created an automobile object, and added our function to it. "this" is the automobile object, because we are invoking the function on the automobile object.
Thus, "this" is a dynamic quantity – it is not cast in stone when the function is defined, but refers to the current object that the function is being invoked on.