I am confused about the keyword 'this' in

2020-02-29 03:07发布

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.

2条回答
爷的心禁止访问
2楼-- · 2020-02-29 03:15

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

查看更多
▲ chillily
3楼-- · 2020-02-29 03:16

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.

查看更多
登录 后发表回答