【问题标题】:javascript context arrow function [duplicate]javascript上下文箭头函数[重复]
【发布时间】:2018-01-21 21:16:41
【问题描述】:

我有以下代码:

const person = {
  name: 'Bob',
  greet: () => {
    console.log(`Hi, my name is ${this.name}`);
  }
};

person.greet();

由于某种原因,它输出:

Hi, my name is undefined

我希望它输出:

Hi, my name is Bob

【问题讨论】:

  • 为什么会这样?箭头函数绑定的范围不是您正在创建的对象,this您正在创建它的位置

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

箭头函数没有自己的this;使用了封闭执行上下文的 this 值

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

例子:

// An arrow function does not have its own this
// this of enclosing context is used
window.something = 'Yo yo yo'; 
const data = {
  something: 'Eduardo Stuart',
  
  arrowPrintName: () => {
    console.log(this.something) // this will print "window.something" instead
  },

  shortPrintName () {
    console.log(this.something) // this will print eduardo stuart
  }
}

data.arrowPrintName();
data.shortPrintName();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 2017-02-05
    • 2023-03-08
    • 2022-11-27
    • 2020-11-08
    • 2020-03-07
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多