Object Hierarchy and Inheritance in JavaScript
This paper assumes that you're already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects. For information on this subject, see Chapter 10, "Object Model," in the JavaScript Guide.
The sections in this paper are:
Employee
class could represent the set of all employees. An instance, on the other hand, is the instantiation of a class; that is, one of its members. For example, Victoria
could be an instance of the Employee
class, representing a particular individual as an employee. An instance has exactly the properties of its parent class (no more, no less). A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or even at runtime. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.
In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to use to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.
JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.
In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the
Employee
class includes only name
and dept
properties and Manager
is a subclass of Employee
that adds the reports
property. In this case, an instance of the Manager
class would have all three properties: name
, dept
, and reports
. JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the
Employee
-Manager
example, but you use slightly different terminology. First you define the Employee
constructor function, specifying the name
and dept
properties. Next, you define the Manager
constructor function, specifying the reports
property. Finally, you assign a new Employee
object as the prototype
for the Manager
constructor function. Then, when you create a new Manager
, it inherits the name
and dept
properties from the Employee
object. In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at runtime. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at runtime you can add or remove properties from any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.
Table 1 gives a short summary of some of these differences. The rest of this paper describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.
Table 1 Comparison of class-based (Java) and prototype-based (JavaScript) object systems
The Employee Example
The rest of this paper works with the simple employee hierarchy shown in Figure 1.Figure 1 A simple object hierarchy
Employee
has the propertiesname
(whose value defaults to the empty string) anddept
(whose value defaults to"general"
).Manager
is based onEmployee
. It adds thereports
property (whose value defaults to an empty array, intended to have an array ofEmployee
objects as its value).WorkerBee
is also based onEmployee
. It adds theprojects
property (whose value defaults to an empty array, intended to have an array of strings as its value).SalesPerson
is based onWorkerBee
. It adds thequota
property (whose value defaults to 100). It also overrides thedept
property with the value"sales"
, indicating that all salespersons are in the same department.Engineer
is based onWorkerBee
. It adds themachine
property (whose value defaults to the empty string) and also overrides thedept
property with the value"engineering"
.Creating the Hierarchy
There are several ways you can define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application. We'll get into all that later.Employee
definitions below are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript and you need to create an explicit constructor method for the Java class.
JavaScriptJava function Employee () {
this.name = "";
this.dept = "general";
}public class Employee {
public String name;
public String dept;
public Employee () {
this.name = "";
this.dept = "general";
}
}Manager
and WorkerBee definitions show the difference in how you specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of theprototype
property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.
JavaScriptEngineer
andSalesPerson
definitions create objects that descend fromWorkerBee
and hence fromEmployee
. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of thedept
property with new values specific to these objects.
JavaScriptNOTE: As described earlier, the term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual member of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that
Figure 3 Creating objects with the simple definitionsjane
is an instance ofEngineer
. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript, we can use them informally to refer to objects higher or lower in the prototype chain.Object Properties
This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at runtime.Inheriting Properties
Assume you create themark
object as aWorkerBee
as shown in Figure 3 with this statement:mark = new WorkerBee;
When JavaScript sees thenew
operator, it creates a new generic object and passes this new object as the value of thethis
keyword to theWorkerBee
constructor function. The constructor function explicitly sets the value of theprojects
property. It also sets the value of the internal__proto__
property to the value ofWorkerBee.prototype
. (That property name has 2 underscore characters at the front and 2 at the end.) The__proto__
property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variablemark
to that object.mark
object (local values) for the propertiesmark
inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value isn't there locally, JavaScript checks the prototype chain (using the__proto__
property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object doesn't have the property. In this way, themark
object has the following properties and values:mark.name = "";
The
mark.dept = "general";
mark.projects = [];mark
object inherits values for thename
anddept
properties from the prototypical object inmark.__proto__
. It is assigned a local value for theprojects
property by theWorkerBee
constructor. Simply put, this gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in "Property Inheritance Revisited".WorkerBee
. You can, of course, change the values of any of these properties. So, you could give specific information formark
as shown here:mark.name = "Doe, Mark";
mark.dept = "admin";
mark.projects = ["navigator"];Adding Properties
In JavaScript at runtime you can add properties to any object. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you simply assign a value to the object, as in:mark.bonus = 3000;
Now, themark
object has abonus
property, but no otherWorkerBee
has this property.specialty
property to all employees with the following statement:Employee.prototype.specialty = "none";
As soon as JavaScript executes this statement, themark
object also has thespecialty
property with the value of"none"
. Figure 4 shows the effect of adding this property to theEmployee
prototype and then overriding it for theEngineer
prototype.More Flexible Constructors
The constructor functions used so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. Figure 5 shows one way to do this.
JavaScriptthis.name = name || "";
The JavaScript logical OR operator (||
) evaluates its first argument. If that argument is converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see ifname
has a useful value for thename
property. If it does, it setsthis.name
to that value. Otherwise, it setsthis.name
to the empty string. This paper uses this idiom for brevity; however, it can be puzzling at first glance.Engineer
:jane = new Engineer("belau");
Jane's properties are now:jane.name == "";
Notice that with these definitions, you cannot specify an initial value for an inherited property such as
jane.dept == "general";
jane.projects == [];
jane.machine == "belau"name
. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.Engineer
constructor:function Engineer (name, projs, mach) {
Assume we create a new
this.base = WorkerBee;
this.base(name, "engineering", projs);
this.projects = mach || "";
}Engineer
object as follows:jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
JavaScript follows these steps:1. First, the
new
operator creates a generic object and sets its__proto__
property toEngineer.prototype
.2. The
new
operator then passes the new object to theEngineer
constructor as the value of thethis
keyword.3. Next, the constructor creates a new property called
base
for that object and assigns the value of theWorkerBee
constructor to thebase
property. This makes theWorkerBee
constructor a method of theEngineer
object.NOTE: The name of the
base
property is not special. You can use any legal property name;base
is simply evocative of its purpose.4. Next, the constructor calls the
base
method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane"
and["navigator", "javascript"]
) and also the string"engineering"
. Explicitly using"engineering"
in the constructor indicates that allEngineer
objects have the same value for the inheriteddept
property and this value overrides the value inherited fromEmployee
.5. Because
base
is a method ofEngineer
, within the call tobase
, JavaScript binds thethis
keyword to the object created in step 1. Thus, theWorkerBee
function in turn passes the"Doe, Jane"
and["navigator", "javascript"]
arguments to theEmployee
constructor function. Upon return from theEmployee
constructor function, theWorkerBee
function uses the remaining argument to set theprojects
property.6. Upon return from the
base
method, theEngineer
constructor initializes the object'smachine
property to"belau"
.7. Upon return from the constructor, JavaScript assigns the new object to the
You might think that, having called thejane
variable.WorkerBee
constructor from inside theEngineer
constructor, you've set up inheritance appropriately forEngineer
objects. This is not the case. Calling theWorkerBee
constructor ensures that anEngineer
object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to theEmployee
orWorkerBee
prototypes, those properties are not inherited by theEngineer
object. For example, assume you have these statements:function Engineer (name, projs, mach) {
The
this.base = WorkerBee;
this.base(name, "engineering", projs);
this.projects = mach || "";
}
jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
Employee.prototype.specialty = "none";jane
object does not inherit thespecialty
property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:function Engineer (name, projs, mach) {
Now the value of the
this.base = WorkerBee;
this.base(name, "engineering", projs);
this.projects = mach || "";
}
Engineer.prototype = new WorkerBee;
jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
Employee.prototype.specialty = "none";jane
object'sspecialty
property is"none"
.Property Inheritance Revisited
The preceding sections have described how constructors and prototypes provide hierarchies and inheritance in JavaScript. As with all languages, there are some subtleties that were not necessarily apparent in these earlier discussions. This section discusses some of those subtleties.Local versus Inherited Values
Let's revisit property inheritance briefly. As discussed earlier, when you access an object property, JavaScript performs these steps:-
- Check to see if the value exists locally. If it does, return that value.
- If there isn't a local value, check the prototype chain (using the
__proto__
property). - If an object in the prototype chain has a value for the specified property, return that value.
- If no such property is found, the object does not have the property.
function Employee () {
this.name = "";
this.dept = "general";
}function WorkerBee () {
With these definitions, assume you create
this.projects = [];
}
WorkerBee.prototype = new Employee;amy
as an instance ofWorkerBee
with this statement:amy = new WorkerBee;
Theamy
object has one local property,projects
. The values for thename
anddept
properties are not local toamy
and so are gotten from theamy
object's__proto__
property. Thus,amy
has these property values:amy.name == "";
Now assume you change the value of the
amy.dept = "general";
amy.projects == [];name
property in the prototype associated withEmployee
:Employee.prototype.name = "Unknown"
At first glance, you might expect that new value to propagate down to all the instances ofEmployee
. However, it does not.Employee
object, that instance gets a local value for thename
property (the empty string). This means that when you set theWorkerBee
prototype by creating a newEmployee
object,WorkerBee.prototype
has a local value for thename
property. Therefore, when JavaScript looks up thename
property of theamy
object (an instance ofWorkerBee
), JavaScript finds the local value for that property inWorkerBee.prototype
. It therefore does not look farther up the chain toEmployee.prototype
.function Employee () {
this.dept = "general";
}
Employee.prototype.name = "";function WorkerBee () {
this.projects = [];
}
WorkerBee.prototype = new Employee;amy = new WorkerBee;
Employee.prototype.name = "Unknown";
In this case, thename
property ofamy
becomes"
Unknown"
.Determining Instance Relationships
You may want to know what objects are in the prototype chain for an object, so that you can tell from what objects this object inherits properties. In a class-based language, you might have aninstanceof
operator for this purpose. JavaScript does not provideinstanceof
, but you can write such a function yourself.new
operator with a constructor function to create a new object, JavaScript sets the__proto__
property of the new object to the value of theprototype
property of the constructor function. You can use this to test the prototype chain.__proto__
object as follows:chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
With this object, the following statements are all true:chris.__proto__ == Engineer.prototype;
Given this, you could write an
chris.__proto__.__proto__ == WorkerBee.prototype;
chris.__proto__.__proto__.__proto__ == Employee.prototype;
chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;instanceOf
function as follows:function instanceOf(object, constructor) {
With this definition, the following expressions are all true:
while (object != null) {
if (object == constructor.prototype)
return true;
object = object.__proto__;
}
return false;
}instanceOf (chris, Engineer)
But this expression is false:
instanceOf (chris, WorkerBee)
instanceOf (chris, Employee)
instanceOf (chris, Object)instanceOf (chris, SalesPerson)
Global Information in Constructors
When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use this definition forEmployee
:var idCounter = 1;
function Employee (name, dept) {
With this definition, when you create a new
this.name = name || "";
this.dept = dept || "general";
this.id = idCounter++;
}Employee
, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement were:victoria = new Employee("Pigbert, Victoria", "pubs")
harry = new Employee("Tschopik, Harry", "sales")victoria.id
is 1 andharry.id
is 2. At first glance that seems fine. However,idCounter
gets incremented every time anEmployee
object is created, for whatever purpose. If you create the entireEmployee
hierarchy we've been working with, theEmployee
constructor is called every time we set up a prototype. That is, assume you have this code:var idCounter = 1;
function Employee (name, dept) {
this.name = name || "";
this.dept = dept || "general";
this.id = idCounter++;
}function Manager (name, dept, reports) {...}
Manager.prototype = new Employee;function WorkerBee (name, dept, projs) {...}
WorkerBee.prototype = new Employee;function Engineer (name, projs, mach) {...}
Engineer.prototype = new WorkerBee;function SalesPerson (name, projs, quota) {...}
SalesPerson.prototype = new WorkerBee;mac = new Engineer("Wood, Mac");
Further assume that the definitions we've omitted here have thebase
property and call the constructor above them in the prototype chain. In this case, by the time themac
object is created,mac.id
is 5.function Employee (name, dept) {
When you create an instance of
this.name = name || "";
this.dept = dept || "general";
if (name)
this.id = idCounter++;
}Employee
to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for anEmployee
to get an assigned id, you must specify a name for the employee. In our example,mac.id
would be 1.No Multiple Inheritance
Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.function Hobbyist (hobby) {
this.hobby = hobby || "scuba";
}function Engineer (name, projs, mach, hobby) {
this.base1 = WorkerBee;
this.base1(name, "engineering", projs);
this.base2 = Hobbyist;
this.base2(hobby);
this.projects = mach || "";
}
Engineer.prototype = new WorkerBee;dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")
Further assume that the definition ofWorkerBee
is as we've previously seen it. In this case, the dennis object has these properties:dennis.name == "Doe, Dennis"
So
dennis.dept == "engineering"
dennis.projects == ["collabra"]
dennis.machine == "hugo"
dennis.hobby == "scuba"dennis
does get thehobby
property from theHobbyist
constructor. However, assume you then add a property to theHobbyist
constructor's prototype:Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
Thedennis
object does not inherit this new property.-