JavaScript 中的箭头函数中的 "this" 是什么

What is "this" in an arrow function in JavaScript

我对箭头函数中的“this”指向什么有疑问:

// run this file in nodejs by: node test_this.js
const obj = {
  scope:this,
  func1:()=>{return this},
  func2:function(){
    const fn = ()=>this;
    return fn(); 
  }
}
console.log("0",obj.scope); // module.exports
console.log("1",obj.func1()); // module.exports
console.log("2",obj.func2()); //obj

const newFunc2 = obj.func2;
console.log("newFunc2",newFunc2()); //global

据我所知,箭头函数没有自己的“this”。一旦声明了箭头函数,范围就决定了“this”,并且永远不会改变。但是为什么 console.log("2",obj.func2()); 输出 obj?以及为什么 console.log("newFunc2",newFunc2()); 打印不同的结果 global?

您的 obj 声明的 this 的词法值为 module.exports。这是声明 obj 变量时 this 的值。

  1. 所以,这就解释了为什么 obj.scopemodule.exports,因为那是 this 在你的对象被声明和初始化时的值scope:this,

  2. 正如您似乎已经知道的那样,在 obj.func1() 中使用对象调用时箭头函数声明不会像 this 那样执行 obj。相反,它使用 this 的词法版本(声明时的版本)。正如 obj.scope 所示,this 的词法值为 module.exports。因此,console.log("1",obj.func1()) 的结果是预期的 module.exports(因为 func1 被定义为箭头函数。

  3. 然后,使用obj.func2(),它被声明为一个普通函数,所以func2内部的this的值被调用为obj.func2() ] 将是 obj。这就是像 obj.func2() 这样的方法函数调用在 Javascript 中的工作方式(只要该函数是普通函数定义或方法定义,而不是箭头函数)。

最后,当你这样做时:

const newFunc2 = obj.func2;

您正在获取对 func2 方法的引用,完全是单独的。您只隔离了方法,它不再与对象有任何关联。所以,当你这样称呼它时:

console.log("newFunc2",newFunc2());

obj 引用的对象完全消失,this 值将设置为与任何普通函数调用相同的值。 this 的值将被设置为 undefined 如果你是 运行 严格模式或 global 值如果不是 运行 严格模式。

有关所有这些工作原理的回顾或对未来的参考,请参阅:

The 6 ways the value of this is determined inside a function at execution time.

当您将 obj.func2 分配给 newFunc2 时,该函数将被复制到新变量,不再与 obj 相关联。因此,当您调用 newFunc2() 时,它在该范围内通过 this 引用 window 对象。下面的示例演示了 obj.func2 在定义时没有 className 的任何信息。当我们在 class MyObj 中复制函数 func2 时,this 现在引用新的 class,因此你得到日志 this.className = 'MyObj'

const obj = {
  scope:this,
  func1:()=>{return this},
  func2:function(){
    const fn = ()=>this;
    console.log(this.className)
    return fn(); 
  }
}

class MyObj {
  constructor() {
    this.className = 'MyObj'
    this.obj()
  }
  obj() {
    this.func2 = obj.func2
  }
  print() {
    this.func2()
  }
}

var myObj = new MyObj()
myObj.print()

.

JavaScriptthis关键字指的是它所属的对象。

它根据使用的地方有不同的值:

在方法中,this 指的是所有者对象。 单独的,this指的是全局对象。 在函数中,this 指的是全局对象。 在函数中,在严格模式下,this 是未定义的。 在事件中,this 指的是接收事件的元素。 call() 和 apply() 等方法可以将 this 引用到任何对象。

严格模式下,单独使用时,this也引用全局对象[object Window]

“使用严格”; 变量 x = 这个; // x 等于 [object Window]