Inheritance

Objects have attributes. In both JavaScript and Python the statements

value = a.name               # Get the name of 'a'.
a.name = value               # Set the name of 'a'.

respectively set and get the name attribute of the object a. Inheritance is where an object gets some its attributes from one or other more objects.

JavaScript and Python handle inheritance differently. Here we describe what JavaScript does, and later [where] we compare with Python.

Tree

In JavaScript all objects are part of an inheritance tree. Each object in the tree has a parent object, which is also called the prototype object (of the child). There is a single exception to this rule, which is the root of the tree. The root of the tree does not have a parent object.

You can’t get far in JavaScript without understanding the inheritance tree.

Get

When JavaScript needs to get an attribute value of an object, it first looks up the name of the attribute in the object’s dictionary. If the name is a key in the dictionary, the associated value is returned.

If the name is not a key, then the process is repeated using the object’s parent, grandparent, and so on until the key is found. If the key is not found in this way then (see Missing keys) undefined is returned.

Set

When JavaScript needs to set an attribute value of an object it ignores the inheritance tree. It simply sets that value in the object’s dictionary. With Python its just the same. (However, JavaScript’s Pseudo objects (stub) are don’t behave in this way.)

Root

When the interpreter starts up, the root of the tree is placed at Object.prototype.

Every object inherits from the root, although perhaps not directly. Here’s an example:

js> root = Object.prototype
js> a = {}
js> a.name === undefined
true
js> root.name = 'gotcha'
js> a.name
gotcha

Once we give root a name attribute every other object, including those already created and those not yet created, also has a name attribute with the same value.

However, this does not apply if name is found earlier in the tree. We continue the previous example to show this, and the behaviour of set.

js> a.name = 'fixed'
js> a.name
fixed
js> root.name
gotcha

Using create

Any tree can be constructed from its root, together with a command create(parent) that returns a new child of the given parent node.

In JavaScript the create function is not built in (although perhaps it should be). However, it’s easy to write one [link], once you know enough JavaScript.

Here’s an example of its use:

js> a = {}
js> b = create(a)
js> a.name = 'apple'
apple
js> b.name
apple

And a continuation of the example:

js> c = create(b)
js> c.name
apple
js> b.name = 'banana'
banana
js> c.name
banana

Note

JavaScript uses an inheritance tree. By using create, we can create any inheritance tree. All JavaScript objects are in this tree.

Table Of Contents

Previous topic

JavaScript objects

Next topic

Functions

This Page