Reputation:
I have a question relating with using if statement within my prototype constructor.
What I am trying to do:
Code ** NOT WORKING
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
However my error is how I wrote the if statement. Without giving me the solution, could you please direct me on where my mistake was made? Thank you.
Upvotes: 0
Views: 68
Reputation:
UPDATE: Working Code:
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
Upvotes: 0
Reputation: 350137
The problem is that if you call the method repeatedly, the price will keep decreasing (for fruit).
Also the else
clause is doing nothing really: you assign a value that was already assigned.
Instead of storing the calculation result back in this.price
, return it as the function result. That way this.price
remains the same (no unexpected side effects), and can be controlled by the user of the object. The method then only returns the result:
var result = fruit.calculatePrice();
Now fruit.price
will still be the original 10, but result
will be 9.5
Optionally, you could let the function store the result also as an object property, but then it should better be a different one (e.g. this.calculatedPrice
).
NB: As requested, the actual solution code is not provided. Let me know if you need more.
Upvotes: 0
Reputation: 1544
You didn't describe what are your expectations and actual outcome of your code. But one thing that came to mind is, that you forgot to return this.price
in your calculatePrice method, so result is undefined
instead of price. You get result even with your current version, but you have to do it explicitly by checking price property of an instance eg. fruit.price
. And also price will mutate with every calculatePrice method call. Instead assign this.price
to local variable, do the calculation on that variable and return it.
Upvotes: 1