JavaScript 基础:从函数到类的全面解析
1. 箭头函数的 this 值问题
在 JavaScript 中,使用箭头函数时可能会遇到 this 值的问题。比如下面的代码:
let hat = {
name: "Hat",
_price: 100,
priceIncTax: 100 * 1.2,
set price(newPrice) {
this._price = newPrice;
this.priceIncTax = this._price * 1.2;
},
get price() {
return this._price;
},
writeDetails: () =>
console.log(`${this.name}: ${this.price}, ${this.priceIncTax}`)
};
这里的 writeDetails 是一个箭头函数,由于箭头函数没有自己的 this 值,且没有被能提供 this 值的常规函数包裹,所以输出会是 undefined 。为了解决这个问题,我们需要使用常规函数并结合 bind 方法来固定 this 值,修改后的代码如下:
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



