This pattern refers to the invocation of a function that is not defined as a member of an object. This is the most basic way to define a function, and it includes both function declarations:
function hello() {
alert('hello');
}
and function expressions:
var hello = function() {
alert('hello');
}
Functions invoked in this way have access to the this keyword, and its value is the global object. This is probably not what you would expect to see. You might anticipate this to refer to the parent function's scope, but it does not. Here is an example.
var obj = {};
obj.add = function(val1, val2) {
var inner = function() {
this.sum = val1 + val2;
}
inner();
}
obj.add(2, 4);
You might expect obj.sum to equal 6, but it does not!
console.log(obj.sum);
> undefined
Rather the global object now has a sum attribute. Take a look:
console.log(sum);
> 6
This is not good. Whenever possible we want to avoid clouding the global namespace. There is a conventional way around this problem, and the solution involves a new variable called that (as a Python guy, I also like self). Check out this example:
var obj = {};
obj.add = function(val1, val2) {
var that = this;
var inner = function() {
that.sum = val1 + val2;
}
inner();
}
obj.add(2, 4);
You should notice a small change. The first line of the add method now shows var that = this;. In this case, we are setting the value of this (which refers to the obj object) to the variable that.
Now within the inner function, since the this keyword refers to the global object, we want to use that to refer to the obj object. Now you can log obj.sum and get what you might expect:
console.log(obj.sum);
> 6
You should remember that when invoking a function on its own (not as a member of an object), this will refer to the global object.