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

时间:2013-02-13 05:36:18

标签: javascript scope 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

所以关于范围链,所有变量都已解决,现在我有一个问题。

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

因此,如果我们有以下功能:

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

“this”关键字总是让我困惑!

有人请以简单的方式详细解释。

2 个答案:

答案 0 :(得分:3)

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

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

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

    如果我们使用对象'o' -

    调用对象'o'的方法'f'
    o.f()// in method f, 'this' refers to o inside the method o
    
  2. 如果未通过对象调用该函数,则当前窗口对象是该函数的调用上下文或this值。例如 -

    function f(){
        //do something
    }
    
    //calling f
    f();// 'this' will refer to current window object 
    
  3. 在您的情况下,这指的是当前窗口对象,而this.a是对您在全局范围中定义的函数a的引用。

    此外,调用它时可以提供函数的调用上下文或'this'值。请检查Function.prototype.call method - JavaScript | MDNFunction.prototype.apply method - JavaScript | MDN

答案 1 :(得分:0)

this关键字指的是函数的范围。在上面的代码中, this.a 将打印 undefined ,因为没有名为a的变量。 this关键字用于引用当前本地范围而不是全局范围。因此,如果你在函数b中有一个名为a的变量,那么this.a将引用函数b中定义的变量而不是它之外的变量。虽然在函数b之外引用它将引用全局范围。

相关问题