gpt4 book ai didi

JavaScript 上下文箭头函数

转载 作者:行者123 更新时间:2023-12-01 02:30:02 24 4
gpt4 key购买 nike

我有以下代码:

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

最佳答案

An arrow function does not have its own this; the this value of the enclosing execution context is used

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

关于JavaScript 上下文箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48371802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com