This is an example:
function one() {
var a = 1;
two();
function two() {
var b = 2;
three();
function three() {
var c = 3;
alert(a + b + c); // 6
}
}
}
one(); //calling the function
Now when we call function one(), the result is 6
.
So it's all about scope chain, all variables are resolved, now I have one question.
Why do we need this "this" keyword when all variables are getting resolved through scope chain?
So if we have the following function:
function a() {
var a = 'function a';
function b() {
var b = 'function b';
alert (a); //will be function a, without keyword this
alert (this.a); // what will be the effect of this line
}
}
The "this" keyword always confuses me!
Someone please explain in a simple way and in detail.
They keyword
this
is resolved in the following ways in the a function in JavaScript -When a function is invoked on or through an object, that object is the invocation context or 'this' value for the function. For example -
if we call the method 'f' of object 'o' using object 'o' -
If the function is not invoked on or not through an object,current window object is the invocation context or
this
value for the function. For example -In your case, this refers to current window object and
this.a
is a reference to the function a, which you have defined in the global scope.In addition, invocation context or 'this' value for the function can be supplied while calling it. Please check Function.prototype.call method - JavaScript | MDN and Function.prototype.apply method - JavaScript | MDN
The this keyword refers to the scope of the function. In your above code the this.a will print undefined since there is no variable named a. The this keyword is used to refer the current local scope and not the global scope. so if you had a variable named a in your function b then this.a will refer the variable defined in the function b and not outside of it. Whereas referring this outside the function b will refer the global scope.