繁体   English   中英

class 中的箭头 function

[英]Arrow function in class

代码 1:

class X1 {
  x = 1;
  get = () => this;
}
a = new X1();
console.log(a.get());

代码 2:

var X1={
    x:1,
    get:()=>this
}
console.log(X1.get())

我不知道为什么代码 1 的结果是 X1,但代码 2 是 Window。 希望大家能帮帮我!!

Class 字段是用于在构造函数中分配的语法糖。 代码 1 相当于:

class X1 {
  constructor() {
    this.x = 1;
    this.get = () => this;
  }
}

在构造函数内部, this指的是正在创建的实例 - a 箭头函数从它们的外部 scope 继承this一点。 所以this.get = () => this; 导致返回的this与外部 scope - 实例或a中的this相同。

在代码 2 中,外部 scope 是顶层 顶层的this是全局 object (在浏览器中,即window )或undefined 因此,返回this的箭头 function get返回顶层的this - 在浏览器中的草率模式下,即 window。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM