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 -
var o = {
f : function(){
//do something
}
}
if we call the method 'f' of object 'o' using object 'o' -
o.f()// in method f, 'this' refers to o inside the method 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 -
function f(){
//do something
}
//calling f
f();// 'this' will refer to current window object
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With