New course! Every coder should learn Generative AI!
Try a free lesson0
Stack error message
I'm getting a maximum stack error message, this program is supposed to discount 15% off of the original price. function main() { var prodID = readLine(); var price = parseInt(readLine(),10); var discount = parseInt(readLine(),10); var prod1= new Product(prodID, price); console.log(prod1.prodID + " price: " + prod1.price); prod1.changePrice(discount); console.log(prod1.prodID + " new price: " + prod1.price); } function Product(prodID, price) { this.prodID = prodID; this.price = price; this.changePrice = function(discount) { //your code goes here var p = price * discount; var newPrice = price - p; var t = new Product(price) t.changePrice(newPrice); } }
5 Answers
+ 1
changePrice() should a setter method for price
In your attempt you try to create a Product object inside the changePrice() method and then call itself on this object?
Just assign the new price to this.price – and mind that discount is given as integer number (not a proportion)!
0
Thank you, I had to reset the code and divide variable discount by 100 then I was able to subtract the discount.
I thought the discount was going to be fixed at 0.15, 15%.
This way of course is more interesting but this is very complicated for someone who learned a little bit of the Basic programming language back in the early 90's when you had to use the "goto" statement to jump around code.
I think I could have written this program more easily using C++ taking input from the user and just plain functions and "cout" commands to display the result.
I'm gonna have to study this because I have no clue about what you meant about "In your attempt you try to create..........then call itself on this object?
0
It would be nice if there was a way to look at the flow of this code here from start to finish.
0
I mean this code here now that it works correctly:
function main() {
var prodID = readLine();
var price = parseInt(readLine(),10);
var discount = parseInt(readLine(),10);
var prod1= new Product(prodID, price);
console.log(prod1.prodID + " price: " + prod1.price);
prod1.changePrice(discount);
console.log(prod1.prodID + " new price: " + prod1.price);
}
function Product(prodID, price) {
this.prodID = prodID;
this.price = price;
this.changePrice = function(discount) {
//your code goes here
discount = discount/100;
var newPrice = price - ( discount * price );
this.price = newPrice;
}
}
0
I think I understand the flow of this code now.
//this part doesn't make a call
// it only display user input at the
//moment
console.log(prod1.prodID + " price: " + prod1.price);
// this part here makes a function call
// to change to a discounted price
prod1.changePrice(discount);
console.log(prod1.prodID + " new price: " + prod1.price);