为什么分配了箭头功能的属性在声明时将其绑定? [英] how come a property assigned arrow function binds this at declaration?

查看:96
本文介绍了为什么分配了箭头功能的属性在声明时将其绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此类

class Car {
  foo() {
    console.log(this)
  }

  bar = () => {
    console.log(this)
  }

  baz = function() {
    console.log(this)
  }
}


let car = new Car();

let a = car.foo;
let b = car.bar;
let c = car.baz;



a() // undefined

b() // car object

c() // undefined

属性分配箭头功能如何绑定 this 在它的声明处?

How come the property assigned arrow function binds the value of this at it's declaration ?

我认为箭头函数使用执行上下文的 this 值,而不是声明。

I thought arrow functions use the this value of the execution context, not declaration.

推荐答案

这不是ES6代码。您正在使用类字段提案。类字段基本上只是用于编写通常进入构造函数的代码的语法糖。

This is not ES6 code. You are using the class fields proposal. Class fields are basically just syntactic sugar for writing code that normally goes into the constructor.

等效于ES6的

class Car {
  foo() {
    console.log(this)
  }

  constructor() {
    this.bar = () => {
      console.log(this)
    };

    this.baz = function() {
      console.log(this)
    };
  }
}




我认为箭头功能使用执行上下文的 this 值,而不是声明。

I'我不太确定这是什么意思,但是箭头函数中的 this 值可以像其他变量一样按词法解析。定义箭头函数时,已经设置了执行上下文的 this 值。

I'm not quite sure what you mean by this but the this value inside an arrow function resolves lexically, just like any other variable. And the this value of the enclosing execution context is already set when the arrow function is defined.

给出如何分类字段起作用,我们现在可以看到arrow函数为什么要引用实例:在构造函数 this 内部引用实例,而arrow函数解析 this 从字面上看。

Given how class fields work we can now see why the arrow function has the reference to the instance: Inside the constructor this refers to the instance and arrow functions resolve this lexically.

这篇关于为什么分配了箭头功能的属性在声明时将其绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆