Any function in ECMAScript ( core language that JS is based on ) is a separate execution context, and runs individually from one another. Inside of each execution context, this
refers to the object in question, defaulting to whatever the function is attached to.
function foo() {
alert(this===window)
}
Would alert true, because the window is the object which owns the 'foo' method. Any variables defined in a function become accessed through that function's unique scope chain, environment.
function world() {
var name = 'global';
alert(name)
}
would alert 'global' obviously.
function world() {
var name = 'global';
(function() {
var name = 'country';
alert(name)
})();
alert(name)
}
In the latest example, when the first alert is invoked, Javascript determines that in the scope chain of the inner function that the identifier name
is defined, so it doesn't have to look up the scope chain to grab it.
In the second alert invocation, name
is also defined in the same context and alerts 'global';
function world() {
var name = 'global';
(function() { alert(name) })();
}
In this example, the name
identifier is not defined in the same context and thus it has to travel up the scope chain to the outer function where name is defined, and it alerts global.
Reference: