JavaScript Objects – Simple Inheritance

JavaScript Objects Continued…

Previous JavaScript article: Objects Introduction.

In this article let’s see how to use JavaScript inheritance though a simple hierarchy or chain of objects. As a reminder, JavaScript objects are simply collections of key/value pairs, where the keys are unquoted strings, such as brand and model, year, and servicing. Values can be simple like numbers and booleans or complex like arrays or other objects. These key/value pairs are often called properties in objects.

Simple Object Inheritance

Simple example of object inheritance

 

 

 

 

 

 

 

 

 

 

In the above example we create a new object (lines 3 to 9) with three properties (key/value pairs). The capital first letter of the object name is to show that this will be a template for other objects.  Then we use the Object.create function (line 12) to create a new empty object with a link to the Car object. So JavaScript now has a search path to find properties, as demonstrated in line 13. The property brand does not exist in the volvo object, so JavaScript uses the link to check the Car object for a local brand property and with success. And the same applies to the tax property (line 14).

Creating a local property

However the volvo object needs its own property value for brand. We do that in line 17 with the assignment command. An assignment will do one of two things: (1) if the local property is missing then the assignment will create one; or (2) if it exists, then JavaScript will simply modify its value. Effectively, the new volvo.brand property now blocks the Car.brand property.

As a general principle, create shared properties at the top of the chain (e.g Car) and individual properties at the bottom (e.g. volvo), where JavaScript starts searching.

Finally, the last line demonstrates three possible search outcomes: (1) use of local property; (2) use of shared property (higher up hierarchy), if no local property; and (3) unable to find property in the whole search chain (undefined).

In the next article we shall look at better ways of creating a new object, adding properties, and modifying property values. Alex McCullie

Leave a Reply

Your email address will not be published. Required fields are marked *