繁体   English   中英

两个箭头功能有什么区别?

[英]What is the difference between the two arrow functions?

我了解箭头功能中的“ this”在上执行上下文中指向此。

 var name = 'aaa'; const person = { name: 'bbb', getName: () => {return console.log(this.name)} } person.getName(); 

所以我知道getName()在上面的代码中记录了全局对象的名称。

 const name = 'aaa'; const Person = function() { this.name = 'bbb'; this.getName = () => {return console.log(this.name)} } const test = new Person(); test.getName(); 

但是,此代码中的测试对象是作为Person构造函数创建的对象。 因此,我认为测试对象的getName()与上述代码在对象的方法中使用的相同。 我理解错了什么?

const person = {
    name: 'bbb',
    getName: () => {return console.log(this.name)}
}

这样,您已经定义了一个具有2个属性namegetName的对象名称person name的类型是字符串,而getName的类型是函数( 箭头函数 )。 普通函数和箭头函数之间的区别之一是使用this关键字的方式。

由于person是一个对象而不是一个函数,因此无法创建此对象的新实例:

var p = new person(); // Error: person is not a constructor

否则,如果Person是一个函数

const Person = function() {
    this.name = 'bbb';
    this.getName = () => {return console.log(this.name)}
}

然后,您可以创建它的新实例:

const test = new Person();

此功能也有2个属性。 这两个属性的类型与第一个相同。


对于您的问题,建议您在函数中检查this对象:

 const person = { name: 'bbb', getName: () => {console.log(this)} } person.getName(); 

 const Person = function() { this.name = 'bbb'; this.getName = () => {console.log(this)} } const test = new Person(); test.getName(); 

箭头功能中的this功能由封闭的词法上下文定义。 常规对象未在对象本地定义this 因此,查找继续向外进行,您获得了全局对象。 在另一方面,当您使用new运营商,它创建一个对象,并明确设置的功能this指向该对象。 这是值this箭头功能会看到,因为这是值this在不久的词汇语境。

这是令人困惑的,因为常规函数使用不同的规则来定义this 例如,这适用于普通对象:

 const person = { name: 'bbb', // non-arrow function getName() { console.log(this.name)} } person.getName(); 

您可以通过组合示例向外查看封闭的上下文,从而看到箭头函数定义this方法的方式:

 const Person = function() { this.fname = 'Bob'; this.obj = { getName: () => { console.log(this.fname)} } } const test = new Person(); test.obj.getName(); 

暂无
暂无

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

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