I am confused about the 'this' keyword in JavaScript

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 the one () function, the result is 6 .

So, everything about the chain of visibility, all the variables are solved, now I have one question.

Why do we need this keyword "this" when all the variables become allowed along the chain of chains?

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 keyword "this" always bothers me!

Someone please explain this in a simple and detailed way.

+5
javascript scope this
source share
3 answers

The this allowed in the following ways in a function in JavaScript -

  • When a function is called in or through an object, this object is a call to the context or the value of this for the function. For example -

     var o = { f : function(){ //do something } } 

    if we call the 'f' method of the object 'o' using the object 'o' -

     of()// in method f, 'this' refers to o inside the method o 
  • If the function is not called or not through the object, the current window object is the call 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 the current window object, and this.a is a reference to the function a that you defined in the global scope.

In addition, a call context may be provided with a call context or the value 'this' for a function. Check out Function.prototype.call Method - JavaScript | MDN and Function.prototype.apply Method - JavaScript | MDN

+3
source share

This keyword refers to the scope of a function. In the above code, this.a will print undefined since there is no variable named a. this keyword is used to refer to the current local area , not to the global area. therefore, if you have a variable named a in your function b, then this.a will refer to the variable defined in function b, and not outside of it. While reference to this outside function b will refer to the global scope.

0
source share

Use of this keyword

Inside an instance or constructor method, this is a reference to the current object — the object whose method or constructor is being called. You can access any member of the current object from an instance method or constructor using this. Using it with a field

The most common reason for using this keyword is that the field is obscured by a method or constructor parameter.

-one
source share

All Articles