Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am confused about the keyword 'this' 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 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.

like image 515
Abdul Raziq Avatar asked Oct 22 '22 17:10

Abdul Raziq


1 Answers

They keyword this is resolved in the following ways in the a function in JavaScript -

  1. 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
    
  2. 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

like image 137
Moazzam Khan Avatar answered Nov 01 '22 16:11

Moazzam Khan