【问题标题】:global & local var and this operator in jsjs 中的全局和本地 var 和 this 运算符
【发布时间】:2016-11-08 04:20:04
【问题描述】:

我对 js 中的 global、local var 和 this 运算符有点困惑。 如果有人可以解释为什么输出是这样,我必须编写示例及其输出:

var x="10";
function f() {
    var x="4";
    alert(this.x);
    function g() {alert(x);}
    g();
}
f();

输出是:alert(10) 然后是 alert(4),为什么?与 this 运算符有什么区别?

第二个例子:

enter code here

 var y="5";
var x="10";
x=y;
function f()
{
    y="4";
     alert(this.y);
     function g() {alert(y);}
     g();
}
alert(y);
f();

输出是:alert(4) 然后 alert(5) anf 然后 alert(4),为什么又是?我看不到的“this”运算符的隐藏语义是什么?

如果有人可以给出 js 中全局、本地、this、范围的一般规则及其极端情况。

【问题讨论】:

  • 当this 总是绑定到调用方法的对象(箭头函数除外)时,这在您的代码中可能是什么对象?您是否将f 作为一种方法应用(例如obj.f())?你看到什么物体了吗?所以this 隐式绑定到全局对象(浏览器中的window)。由于x 和y 在全局范围内(未在函数内定义),因此它们可以在window 中访问。

标签: javascript scope this global local


【解决方案1】:
  • 访问变量(例如x)将指向当前范围中的变量x(例如定义在内部的变量x你的功能)。

  • 但是,this.x 的值取决于 在哪里 调用它。 this 绑定到一个对象,在这种情况下,它指向解析为window.x 的全局window 对象,即全局 x。

您可以找到有关this on MDN 的更多信息,并注意您的代码在strict mode 中的行为会有所不同。

【讨论】:

    【解决方案2】:

    这里有一些解释:

    var x="10";
    function f() {
        var x="4"; // This is a local variable and not a property of f
        alert(this.x); // "this" represent the global scope because you do not a new instance of f with the keyword "new" like this new f()
        function g() {alert(x);} // The x variable reference the parent scope which is f
        g();
    }
    f();
    

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 2016-06-02
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多