Defining an Object Literal
Notice the use of this to access a property of the object from within the object definition. For example, this.street accesses the street property of the object. Line 26 shows one way of accessing an object property. An alternative way is aHouse[‘suburb’]. Also lines 17 and 26 use back quotes (`) to use template literals, the ability to embed variable references into strings without using concatenation (+).
Modifying An Object Literal
We can also change an object literal during the running of the software.
Lines 29 and 30 show two ways of modifying a property value. In line 33 we add a new property, lastInspection, by referring to property that does not exist. One is automatically created. And, finally, use the key word, delete, to a property (line 36). No error occurs if that property does not in fact exist.
Here are some useful examples, including checking if a property actually exists.
You can check for a property using hasOwnProperty as shown in lines 39 and 40. Then there are three examples of accessing object data. Object literals are a great way of organizing code that fulfill similar purposes and avoiding variable name.
I have included the source file listed below for download. All routines are embedded in a self-executing anonymous function (IIFE) to avoid declaring global variables.
by Alex McCullie source file: oop_object_literal