JS初学者疑问:对象定义内用this访问属性为何返回NaN?
为什么对象定义内用
this访问属性会得到NaN?如何在对象内部定义依赖其他属性的属性? 问题原因
在你写的对象字面量代码里,realPrice属性计算时用到的this,并不指向正在创建的airMax1对象。
对象字面量的属性定义是在当前执行上下文里执行的——如果是在全局环境下写这段代码,this指向的是全局对象(浏览器中是window,Node.js中是globalThis)。而全局对象里没有price、appreciation这些属性,所以this.price拿到的是undefined,用undefined做数学运算自然会得到NaN。
而外部赋值的方式能正常工作,是因为此时对象已经创建完成,你通过airMax1直接访问它的属性,能拿到正确的数值,计算结果自然正确。
解决方案
下面是几种在对象定义内实现依赖属性的方法:
1. 使用Getter属性(推荐,支持自动更新)
把realPrice定义为一个getter函数,每次访问这个属性时都会重新计算结果。这样不仅能在对象创建时得到正确值,当其他属性变化时,realPrice也会自动更新:
const airMax1 = { price: 200, appreciation: 8, taxRate: 0.2, get realPrice() { const basePrice = this.price + this.appreciation; return basePrice * (1 + this.taxRate); } }; console.log(airMax1); console.log(airMax1.realPrice); // 输出249.6 // 修改属性后,realPrice会自动重新计算 airMax1.price = 250; console.log(airMax1.realPrice); // 输出309.6
2. 用工厂函数创建对象(一次性计算)
如果不需要realPrice随其他属性变化而更新,可以用工厂函数先计算好结果,再返回完整对象:
function createShoe(price, appreciation, taxRate) { const basePrice = price + appreciation; const realPrice = basePrice * (1 + taxRate); return { price, appreciation, taxRate, realPrice }; } const airMax1 = createShoe(200, 8, 0.2); console.log(airMax1); // 输出包含正确realPrice的对象
3. 使用ES6类(适合批量创建对象)
如果需要创建多个类似的鞋类对象,用类来定义会更规范。可以选择在构造函数里一次性计算realPrice,或者用getter实现动态更新:
构造函数一次性计算:
class Shoe { constructor(price, appreciation, taxRate) { this.price = price; this.appreciation = appreciation; this.taxRate = taxRate; const basePrice = price + appreciation; this.realPrice = basePrice * (1 + taxRate); } } const airMax1 = new Shoe(200, 8, 0.2); console.log(airMax1);
类中使用Getter(支持动态更新):
class Shoe { constructor(price, appreciation, taxRate) { this.price = price; this.appreciation = appreciation; this.taxRate = taxRate; } get realPrice() { const basePrice = this.price + this.appreciation; return basePrice * (1 + this.taxRate); } } const airMax1 = new Shoe(200, 8, 0.2); console.log(airMax1.realPrice); // 249.6
内容的提问来源于stack exchange,提问作者YounesMeftah
相关产品推荐
相关产品推荐

