HTML and CSS Reference
In-Depth Information
Adding functionality to prototypes is a very effective code reuse pattern. As soon as the
functionality is added to that prototype, it is immediately available to all objects that con-
tain that prototype in their prototype chain: even if they were created before the functional-
ity was added to the prototype.
If you are wondering how objects can be given a specific prototype, this will be
explained in more detail below.
Prototypes provide a mechanism to tidy up the code reuse pattern that we used earlier. The
new implementation of clone (which we will rename to extends ) still accepts an object, but
now returns a new empty object with that object set as its prototype.
We will first write the object that will act as the prototype. This is going to contain two
methods, the increase age method we saw earlier, and a new method that returns the full
name of the person as the concatenation of the first and last name. In addition, this imple-
mentation is going to combine object creation, and the addition of methods to the object,
into a single step:
> person = {
getFullName: function() {
return this.firstName+" "+this.lastName;
increaseAge: function() {
Notice that this object is referring to properties that are undefined . It does not include
lastName , firstName or age properties, therefore calling these methods will not produce
very useful results:
> person.getFullName()
Search WWH ::

Custom Search