Enhanced Object Literals
Get introduced to the enhanced object literal and see how to create properties and methods with examples.
We'll cover the following...
Traditional way of creating an object
Creating an object by assigning fields with values from existing variables is a common operation. In the past, this process involved a lot of noisy code.
Example
Let’s use the old way to create an object with a few fields and methods.
Example explanation
-
The
createPerson()function receives a few parameters and uses them to create an object. -
Next, it assigns the value of
nameto a property with the same name and, likewise, assignsagetoage. -
Finally, it creates a computed property whose name is based on the value of the
sportparameter. Previously, this last step was done outside of the initialization because computed properties were not allowed in the object initialization list. -
As you can see from the above output, the code works.
However, this example ...