【发布时间】:2020-08-04 19:44:45
【问题描述】:
谁能告诉我为什么解构会影响对象的this 值。有很多简单的解决方法,但我只想知道这里实际发生了什么。看起来它应该可以工作,但是由于解构导致this 范围发生了一些奇怪的事情。有人知道吗?
这是一个简单的对象:
const user = {
name: 'John',
age: 30,
sayHi() {
console.log(this); // undefined for foo(), but defined for bar()
return `hello, ${this.name}`;
}
};
在 foo 中,我使用解构来访问对象键,但是 this 值在 sayHi() 内部是未定义的。
const foo = ({ sayHi, name }) => {
console.log(sayHi()); // hello, [empty string]
console.log('OUTPUT: foo -> name', name); // John
};
foo(user);
但是在这里,只传递对象而不进行解构,可以按预期工作,并且定义了 this 值。
const bar = person => {
console.log(person.sayHi()); // hello, John
};
bar(user);
【问题讨论】:
标签: javascript scope this destructuring