The proof desk at Harbour Prints now has an order with a live total. Its getter adds up the quantities every time you read total, and its extra setter pushes one more quantity onto the array. Before a customer approves a print run, the desk wants a copy of that order to hand around. Should the copy keep counting, or should it keep the number the customer saw?
Both answers are useful, and JavaScript gives you a tool for each. In this lesson, you’ll see which tool does which, starting with the copy a Pythonista would try first.
Copy the Order the Python Way
In the Python version, the order is an instance of a class with a @property, and copying it with copy.copy() is the natural move:
import copy
class Order:
def __init__(self, quantities):
self.quantities = quantities
@property
def total(self):
return sum(self.quantities)
order = Order([2, 3])
duplicate = copy.copy(order)
order.quantities.append(4)
print(order.total, duplicate.total)
The program prints 9 for both totals. The copy is shallow, so duplicate shares the original’s quantities list. It’s still an Order, so reading total calls the getter each time.
The JavaScript port is the same order from Computing a Property on Demand. With copy.copy() in mind, you’d expect a copy to keep counting too.
A Pythonista would use spread, { ...order }, which builds a new object from another object’s own enumerable properties. It’s shallow, like {**d} for a dict, but a dict can’t hold a property at all, while a JavaScript object can own a getter. Predict both numbers before you run this:
const order = {
quantities: [2, 3],
get total() {
let count = 0;
for (const quantity of this.quantities) count += quantity;
return count;
},
set extra(quantity) {
this.quantities.push(quantity);
},
};
const snapshot = { ...order };
order.extra = 4;
console.log(order.total, snapshot.total);