Last updated
Last updated
Computed properties are properties derived from the value of one or more properties on the current instance. For example, the fullName
property on the Person
class is defined as a method. But, we could define it as a property based on the firstName
and lastName
property.
Unlike methods, computed properties are accessed like any other data property defined on the class itself. Likewise, computed properties can optionally be iterated over.
We support the following types of computed properties:
Read-write properties are defined using the computed()
method, and passing it an initialization hash. The should have a getter method, and an optional setter method. Let's see how we can redefine our Person
class using computed properties.
Use the computed()
method to define computed property on the class definition.
We can then just use the computed property like any other data property.
Read-only properties are defined in a similar manner as read-write properties. The main difference read-only properties do not have a set
method on its computed property definition.
Now, anytime we set the fullName
property, it will not change.
Here is an example of defining a constant property named MINIMUM_AGE
on the Person
class.
When you enumerate the properties of an object, computed properties are not included in the enumeration. To enable enumeration of computed properties, add the enumerable
property to the computed property descriptor.
Now, the computed properties will appear when the properties of the parent object are enumerated.
By default, computed properties are not configurable. This means that once a property is defined on a object, it cannot be redefined. For example, neither an extended class cannot change the property definition, nor an object instance during initialization time.
To change this behavior, use the configurable
property on the property descriptor.
Now, you can redefine the property in extended classes and during object initialization.
Constant properties are computed properties that do not change. The behavior of a constant property is therefore similar to that of . The main difference is the constant properties are not computed at run-time. Instead, you must provide its value when you are defining the property.
For , add the property descriptor after the constant value.
For , add the configurable
property to the property descriptor after the value.
How to use computed properties in the object model