Java Reference
In-Depth Information
Warning: Default Values in Prototype Objects Are
Be careful when using the prototype to set default values. They are shal-
low, [5] so any changes to an array or object made by an instance will be re-
flected in the prototype and therefore shared between all instances.
A golden rule to remember is: Never use arrays or objects as a default value
in prototype objects .
An alternative would be to set the default value using the method of provid-
ing default values to functions that we saw in Chapter 4 . For example, the
default value of the food property could be set as " pizza " in the con-
structor function:
var Turtle = function(name,food) { = name; = food || "pizza";
To summarize, the following points should be considered when using constructor functions
and prototype objects to create instances:
• Create a constructor function that deals with any initialization.
• Add any shared properties that remain constant and any shared methods to the pro-
totype object.
• Add any individual properties to the instance by assignment (a mixin could be used
for this, as we'll see later).
• Any extra methods and properties can be added to the prototype later, and will be
added to all instances.
• Be careful when overwriting the prototype object completely―the constructor
class needs to be reset.
To demonstrate, let's create another Turtle instance. Use the constructor function to ini-
tialize an instance:
Search WWH ::

Custom Search