[英]JavaScript - Constructor using Prototype
我有一个关于在原型构造函数中使用if语句的问题。
我正在尝试做的是:
代码**不工作
function Item(name, price){
this.name = name;
this.price = price;
}
Item.prototype.calculatePrice = function() {
if (this.name === 'fruit') {
this.price = this.price * 0.95
} else {
this.price = this.price;
}
}
var ball = new Item('soccer ball', 15);
ball.calculatePrice();
// Expected results: 15
var fruit = new Item('fruit', 10);
fruit.calculatePrice();
// Expected results: 9.5
但是我的错误是我如何编写if语句。 如果不给我解决方案,您能否指导我犯错的地方? 谢谢。
您没有描述代码的期望值和实际结果。 但是想到的一件事是,您忘记了在calculatePrice方法中返回this.price
,因此结果是undefined
而不是price。 即使使用当前版本,您也可以获得结果,但是您必须通过检查实例的price属性来明确地做到这一点,例如。 fruit.price
。 而且价格将随着每次calculatePrice方法调用而发生变化。 而是将this.price
分配给局部变量,对该变量进行计算并返回。
问题是,如果您反复调用该方法,则价格将继续下降(对于水果)。
else
子句实际上并没有做任何事情:您分配一个已经分配的值。
而不是将计算结果存储回this.price
,而是将其作为函数结果返回 。 这样, this.price
保持不变(没有意外的副作用),并且可以由对象的用户控制。 然后,该方法仅返回结果:
var result = fruit.calculatePrice();
现在fruit.price
仍将是原始的10,但result
将是9.5
(可选)您可以让函数也将结果存储为对象属性,但最好是将其作为另一个对象(例如this.calculatedPrice
)。
注意:根据要求,未提供实际的解决方案代码。 让我知道您是否需要更多。
更新:工作代码:
function Item(name, price){
this.name = name;
this.price = price;
}
Item.prototype.calculatePrice = function() {
if (this.name === 'fruit') {
return 0.95 * this.price;
} else {
return this.price;
}
}
var ball = new Item('soccer ball', 15);
ball.calculatePrice();
// => 15
var fruit = new Item('fruit', 10);
fruit.calculatePrice();
// => 9.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.