JavaScript Object Inheritance Part 2

Previous JavaScript Object tutorial: link

Improving JavaScript Inheritance

In the last JavaScript tutorial (link above) we built simple hierarchy or chain from Car object to volvo object. To find a property (or key/value pair) JavaScript checks local properties in the volvo object and, failing that, moves to the Car object. If not found at all, then JavaScript returns undefined. So, just remember that local properties always override inherited ones.

And now to the downside… JavaScript offers very few ways of controlling the adding, changing, and removing object properties. However, lets see what we can do to help.

Creating a JavaScript ‘Template’ Object

Simple example of JavaScript object inheritance
Simple example of object inheritance

 

 

 

 

 

 

 

 

 

Re-writing JavaScript code

Create a JavaScript object with local properties

 

 

This time, I used Object.create to create the Car object linked to an empty object ({}).  And, importantly, we can declare four Car properties as well – tax (value) and setValue, getValue, and toString as functions. So, all objects will share a common tax setting and have access to three helper functions. Also, you’ll notice that I did not declare brand and model in the Car object, as we need those as local to individual cars only.

Property attributes

The power of Object.create comes from assigning attributes. In our example, tax is read-only (writeable: false), while configurable: false means ‘cannot be deleted’. So tax has the same fixed value for all cars.

Next comes three helper functions available to all cars. setValue() restricts updating to local properties, while getValue() to properties that exist. Both throw errors, if these conditions are not met. You may see that as drastic and want change to a different response. Finally toString() formats and returns a car description. Also notice the use of back-ticks (`) to enable template literals with ${} and use of this to identify the calling object.

Coming Up Next…

In the next blog we shall examine how to create the car object, volvo, add another property, set property values, and call a property function. Stay tuned.

Leave a Reply

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