【问题标题】:I am confused about the keyword 'this' in JavaScript我对 JavaScript 中的关键字“this”感到困惑
【发布时间】:2013-02-13 05:36:18
【问题描述】:

这是一个例子:

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”关键字总是让我感到困惑!

请哪位大神简单详细的解释一下。

【问题讨论】:

标签: javascript scope this


【解决方案1】:

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

  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 
    

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 2014-11-28
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多