In this lesson, you will learn about prototypes. A prototype is an object from which other objects inherit properties.
Every object has a prototype by default. Since prototypes are themselves objects, every prototype has a prototype too. (There is only one exception, the default object prototype at the top of every prototype chain.)
In our last post, you learned how to create an object with properties and methods, and then use the new keyword to creates instances of the object. Here’s an example:
The function Cat() acts as an object constructor. Its properties and methods are declared inside it by prefixing them with the keyword this. Objects defined using an object constructor are then instantiated using the new keyword. Now you can easily define multiple instances of Cat, each with its own name.
Now, when a function (in the example above, Dog) is used to create an object with the “new” operator, the resulting object will inherit the properties of Dog.prototype. See that the Dog.prototype object has a constructor property that points back to the Dog function. Consequently, every Dog object (that inherits from Dog.prototype) will also appear to have a constructor property that points back to the Dog function.
Creating Multiple Cat Instances Using Prototype
Use it when you want an object to inherit a method after it has been defined. You can think of prototyping as “attaching” a method to an object after it’s been defined. And all object instances will then instantly share this new behavior.
Our example continue from the previous code:
You can get the prototype using getPrototypeOf() and you can determine if two objects have the same prototype:
Chain of Prototypes
Instead of having a separate instance of a function object for every object, you can make the objects share the method by putting it inside the prototype.
Property Access Errors
It is not an error to query a property that does not exist. If a particular property is not found as its own property or an inherited property, the property access expression o.x evaluates to undefined.
For example, if I am to call see if I can get spot’s mother’s name, the value will be returned as undefined.
This raises a TypeError exception. Unless you are certain the property exists, you should test to be sure properties exist.
Assigning an instance of the parent class to the child class, and then specializing it.
In modern browsers you can also use Object.create() to implement inheritance by passing in the prototype.
Here is an example of creating an object that has the same internal prototype as the Shape object.
- Create Advanced Web Applications With Object-Oriented Techniques
- ECMAScript Language Specification