es6方法中函数内部This的值

Value of This inside a function in es6 method

所以我只是在测试 this 的值在 ES6 class 方法中是如何受到影响的。

谁能解释一下为什么下面代码中内部函数 undefinedthis 的值?

class testingThis {
  outerFunc() {
    console.log("the value of this in outerFunc: ", this);
    function innerFunc() {
      console.log("value of this in innerFunc: ", this);
    }
    innerFunc();
  }
};

var newTest = new testingThis();
newTest.outerFunc();

为什么值 this 没有保留在 ES6(我猜不一定是 ES6)方法中,而是保留在通常的函数中(如下所示):

function a() {
  console.log("this outer: ", this)

  function b() {
    console.log("this inner: ", this)
  }
  b();
};
a();

上面代码中的内部和外部this具有相同的值(window)。

ES6 class 自动进入严格模式。

这意味着任何普通函数调用都会在该函数内将 this 的值设置为 undefined。这就是你所看到的。

仅供参考,这是一个严格模式功能,ES6 的唯一参与是它自动将 class 定义放入严格模式。


在严格模式下,任何普通函数调用都会将该函数内部的 this 设置为 undefined

当不处于严格模式时,任何普通函数调用都会将 this 设置为全局对象,在浏览器中,该对象是 window 对象。


你的问题的新部分是两个普通函数调用,不是在严格模式下,它们都将 this 设置为全局对象。这不是 "preserving" this 的值。它在两个函数调用中都将其设置为全局对象。