我对JavaScript中的关键字'this'感到困惑

问题描述:

这是一个例子:

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

现在当我们调用函数one()时,结果是 6

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.

当所有变量通过范围链解析时,为什么我们需要这个 this 关键字?

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.

他们的关键字在JavaScript中的函数中通过以下方式解析 -

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


  1. 当在对象上或通过对象调用函数时,该对象是调用
    上下文或函数的'this'值。例如 -

  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  
   }
}

如果我们调用对象'o'的方法'f'使用对象'o' -

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


  • 如果未通过对象调用该函数,则当前窗口对象是调用上下文或此函数的值。例如 -

    function f(){
        //do something
    }
    
    //calling f
    f();// 'this' will refer to current window object 
    


  • 在你的情况下,这是指当前窗口对象和 this.a 是对函数a的引用,您已在全局范围中定义。

    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.

    此外,可以在调用函数时提供函数的调用上下文或this值。请查看 Function.prototype.call方法 - JavaScript | MDN Function.prototype.apply方法 - JavaScript | MDN

    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