HTML and CSS Reference
In-Depth Information
Prototypes
We will return now to our discussion of objects in JavaScript.
The
clone
function that we wrote above was our first attempt at code reuse. It allowed us to
reuse or extend an object that we had already written. One problem discussed with the
clone
function was that it took all the properties from the object it was cloning, including proper-
ties that were specific to the cloned instance, such as
firstName
and
lastName
.
JavaScript provides a more elegant mechanism for extending objects called prototypes. In
fact, JavaScript itself is considered a prototype-based language.
If you declare an empty object, you may think that it contains no properties at all:
> obj = {}
You can however execute the following method on the object:
> obj.toString()
"[object Object]"
Where did the
toString
method come from?
All JavaScript objects have a prototype object (this can be
null
in rare instances, but this
scenario can largely be ignored). A prototype object is an object in its own right, and can en-
capsulate properties and methods. If we access a property or method on an object, JavaScript
will first try to access that property or method on the object itself. If the object has no prop-
erty or method with that name it will look for it on the prototype object.
In fact, there can be a whole chain of objects due to the fact that the object that is our proto-
type may itself have a prototype. If no objects in the prototype chain have a property match-
ing the name specified then JavaScript returns a special type called
undefined
.
The prototype of our empty object was provided by
Object.prototype
. This is the only ob-
ject that does not have a prototype of its own, and therefore is the end of the chain.
In order to see the prototype chain in action, we can define our own
toString
implementation
on the empty object.
> obj.toString = function() {
return "I am an object"
};
If we now execute
toString
on this object, the newly defined version will be used:
> obj.toString()