Java Reference
In-Depth Information
Creating Objects from Objects
It's possible to avoid using constructor functions altogether and just use objects to create
more objects. The Object constructor function has a method called create that can be
used to create an object, using the object that is provided as an argument as a prototype. For
example, we can create a Human object that will form the basis for other Human objects.
This is simply created as an object literal:
var Human = {
arms: 2,
legs: 2,
walk: function() { console.log("Walking"); }
}
<< {"arms": 2, "legs": 2, "walk": function ()
{ console.log("Walking"); }}
This will act as a prototype for all other Human objects. Its name is capitalized as it acts
in a similar way to a class in classical programming languages, and it's only used to cre-
ate Human objects. It should follow the same rules for prototype objects that we saw earli-
er―it will contain all the methods that Human objects uses, as well as any properties that
won't change very often. In this case, the properties are arms and legs , and the method is
walk() .
We can create an instance of the Human prototype object using the Object.create()
method:
lois = Object.create(Human);
<< {"arms": 2, "legs": 2, "walk": function ()
{ console.log("Walking"); }}
Extra properties can then be added to each instance using assignment:
lois.name = "Lois Lane";
<< "Lois Lane"
Search WWH ::




Custom Search