liveBook · Manning

Computed property

As explained in Building User-Friendly DSLs

A class property whose value is derived when accessed rather than stored as an independently assigned value.

A computed property derives its value when accessed instead of storing an independently assigned value. In a rental form, the read-only rentalPriceAfterDiscount reflects changes to the price and discount fields. section 11.3

Implement the computed value by:

  • Defining a JavaScript getter on the Rental class. section 11.3
  • Leaving the property uninitialized and not independently settable. section 11.3
  • Rendering the result as a display value, formatted with toFixed(2), rather than as an input field. section 11.3

Rental price after discount

The getter computes the original rental price minus the percentage discount: this.rentalPriceBeforeDiscount - this.discount * 0.01 * this.rentalPriceBeforeDiscount. Access it as rental.rentalPriceAfterDiscount. section 11.3

Listing 11.14 The completed implementation of rentalPriceAfterDiscount with rentalPriceAfterDiscount
get rentalPriceAfterDiscount() {
    return this.rentalPriceBeforeDiscount -
         this.discount * 0.01 * this.rentalPriceBeforeDiscount
}

Shows the completed getter implementation for the rental price after discount. section 11.3

How Building User-Friendly DSLs covers it

How deep it goes
Defines JavaScript getters, demonstrates placeholder and final formulas, and connects access to formatted JSX output.
Examples
Uses Rental, rentalPriceBeforeDiscount, discount, rentalPriceAfterDiscount, and a formatted rental form field.
What it assumes
Assumes JavaScript class and JSX familiarity while introducing getters through a concrete rental calculation.
What you can do after
Apply it via a JavaScript getter to derive and display a rental amount without accepting direct edits.
How it connects
Connects JavaScript getters with classes, form fields, JSX expressions, and percentage discounts.

Also explained in

Compare how 2 books explain computed property →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building User-Friendly DSLs. The section links point to the parts of the book it draws on.