javascript上下文箭头功能

时间:2018-01-21 21:16:41

标签: javascript ecmascript-6 arrow-functions

我有以下代码:

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

1 个答案:

答案 0 :(得分:2)

  

箭头功能没有自己的功能;使用封闭执行上下文的此值

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