Computing a Property on Demand
In this lesson, you give a plain JavaScript object a property that’s worked out each time you read
it. Harbour Prints keeps a proof order’s quantities in a list. In Python, the Order class has a total property, and reading order.total with no
parentheses runs the method and prints 5.
The JavaScript export builds the order as a plain object with no class, and a stored total would go
stale as soon as a quantity changes. An object literal takes a getter as a class does, with the
get keyword before the method name, so get total() plays the part of Python’s @property,
though Python needs a class for its property.
Below it, set extra is a separate property, with only a setter and no getter at all. Assigning
to order.extra would call it with a late quantity, which it pushes onto the list. In Python, a
setter extends a property you’ve already defined, under the same name. Nothing assigns to extra
yet.
The last lines log the total and the descriptor of one key. Every property has a descriptor, the record of its value and its flags. In JavaScript, the word means this per-property record, not Python’s descriptor protocol: