The List
[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:
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.
Trillions to 1
Just the other day I was thinking, if, 31 years ago, the two gametes from which I was formed - those two first cells of me - differed in location by a millimeter, I would not be here today. Someone else would be in my place, someone looking very similar, but it would not be me. I would have never awakened to life, but would have remained non-existent. Someone else - a pseudo-Jonathan-Aquino - would have grown up with my family, attended my school, fallen in love with computers, contributed to society - in my place. All without me knowing it; I would never have been born into reality. I would have remained dormant.
The chances of those two first cells meeting were astronomically low - 1 in trillions. And going further back in time, through the generations, the chances of events happening in just the right place and at just the right time to result in this one meeting of cells: very unlikely. If anything had been slightly different - a rainy day instead of a sunny one, for instance - another Jonathan Aquino, not I, would be living this life.
Yet here I am. Trillions to 1 that I should not have been granted a shot at this life. I'm very lucky.
Videos of Great Speeches: I Have A Dream; JFK's Inaugural Address
Footage of a couple of amazing speeches:
- Martin Luther King, Jr. I Have A Dream
- JFK's Inaugural Address