ChaosGT

Results 4 comments of ChaosGT

```js 'use strict'; class Animal { constructor(name, age) { this.name = name; this.age = age; } sayName = function(){console.log(this.name);}; sayAge = ()=>{console.log(this.age);} } let tom = new Animal('tom',19); let [sayName,...

```js 'use strict'; let tom = { name: 'tom', age: 19, sayName: function(){console.log(this.name);}, sayAge: ()=>{console.log(this.age);}, }; let [sayName, sayAge] = [tom.sayName, tom.sayAge]; sayAge(); // this指向外面的空对象{},输出undefined sayName(); // 抛出错误,this为undefined ``` 那为什么这里面的`sayAge`就无法绑定对象`tom`?

@beiatisi 这跟作用域完全没关系。 @cdswyda 我觉得你的回答完全不对。箭头函数本身根本就没有this,需要在上下文中查找,表现出来就是对this透明;而普通函数是有this的,默认为undefined,通过对象点号调用时赋值this为点号前的对象。可能你连我想要问什么都没看明白。 我仔细想了一下,自己尝试回答一下自己的问题: 之所以字段中的箭头函数能绑定对象的this,应该是和javascript引擎的class语法实现有关。 ```js class Animal extends BaseClass { constructor() { //构造函数的执行过程大概如下: let animal = {}; animal.__proto__ = Animal.prototype; super.constructor.call(animal); 初始化字段(字段属于animal,而不是Animal.prototype) 用户自定义初始化语句 return animal; } } ```...

@phyzess 感谢你给出的babel结果,这样就很清楚了,说到底还是解释器硬绑定,和语法本身关系不大,虽然很方便,但个人觉得这破坏了语言的统一性。 `「箭头函数不具有自己的 this,它的 this 永远是定义时包裹它的代码块的 this」`这句话的后半句是不对的,箭头函数只有作为class的field时候,才会绑定当前对象,是解释器的trick,其它时候都是从执行的上下文中获取,而不是定义时的代码块。