【问题标题】:What is the difference between the two arrow functions?两个箭头函数有什么区别?
【发布时间】:2018-11-23 04:39:14
【问题描述】:

我理解箭头函数中的“this”指向上层执行上下文中的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() 与上面代码中对象方法中使用的 this 相同。我理解错了什么?

【问题讨论】:

    标签: javascript ecmascript-6 arrow-functions


    【解决方案1】:

    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();     

    【讨论】:

    • 如果我理解你@김종현,那么是的,构造函数创建的对象就是对象。对象字面量创建的箭头函数是一个函数。
    【解决方案2】:
    const person = {
        name: 'bbb',
        getName: () => {return console.log(this.name)}
    }
    

    通过这种方式,您已经定义了一个对象名称person,其中包含两个属性namegetNamename 的类型是字符串,而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();
    

    这个函数也有两个属性。两个属性的类型与第一个相同。


    对于您的问题,我建议您检查函数内的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();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 2011-02-20
      • 2013-04-03
      相关资源
      最近更新 更多