JS构造函数中实现商品总价累加功能遇阻求助
Fixing Total Price Tracking for Item Instances
Hey there! Let's break down why your current setup isn't working and get that total price tallying correctly.
What's Going Wrong in Your Code
First, let's look at the core issues with your original implementation:
var totalPriceis a local variable inside the constructor function — every time you create a newItem, this variable gets re-declared from scratch. That means it can't hold a running total across multiple instances.- The immediate function
function addToTotalPrice() { totalPrice += price; }();tries to addpricetototalPrice, but sincetotalPricestarts asundefined, this results inNaN(not a number) right away. - The immediate function here is unnecessary for this use case — it doesn't solve the shared state problem you need for tracking total price.
Solution 1: Use a Static Property on the Constructor
The simplest fix is to attach the total price directly to the Item constructor itself (a static property), so all instances share this value:
function Item(name, price, orderID) { // Initialize the totalPrice static property only once if (typeof Item.totalPrice === 'undefined') { Item.totalPrice = 0; } this.name = name; this.price = price; this.orderID = orderID; // Add the current item's price to the total Item.totalPrice += price; }
Test It Out:
const apple = new Item('Apple', 12, 'ORD-001'); const orange = new Item('Orange', 8, 'ORD-002'); console.log(Item.totalPrice); // Output: 20
Solution 2: Use a Closure for Encapsulation
If you want to keep the total price private (so it can't be modified directly from outside), use a closure to wrap the constructor and the private total variable:
const Item = (function() { // Private total variable, only accessible inside this closure let totalPrice = 0; function Item(name, price, orderID) { this.name = name; this.price = price; this.orderID = orderID; totalPrice += price; } // Add a static method to safely get the total price Item.getTotalPrice = function() { return totalPrice; }; return Item; })();
Test It Out:
const book = new Item('Novel', 15, 'ORD-003'); const pen = new Item('Ballpoint Pen', 2, 'ORD-004'); console.log(Item.getTotalPrice()); // Output: 17
Key Takeaways
- To track a value across all instances of a constructor, you need a shared variable — either attached to the constructor (static property) or hidden in a closure.
- Avoid declaring the total variable inside the constructor itself, as it will reset with every new instance.
- Immediate functions aren't needed here unless you're using them to create a closure for private state.
内容的提问来源于stack exchange,提问作者IncrediblePony
相关产品推荐
相关产品推荐

