Java Reference
In-Depth Information
return this.name + " tickles you until you
cry with
laughter";
}
}
If you redefine the prototype, any child objects will retain the old properties
and methods without receiving any new ones.
You should avoid redefining the prototype after any instances have been cre-
ated, otherwise these instances will behave differently to any instances that
are created later. Any properties and methods should be added to the proto-
type by assignment. The fact that the prototype is live means that all prop-
erties and methods added will be shared with all instances.
It is sometimes seen as a good idea to overwrite the prototype immediately
after its creation, to add lots of properties in one go. But this also causes
unexpected problems, as the prototype will lose its link to the constructor
function:
Turtle.prototype.constructor
<< undefined
If you do use this method, be sure to reset the prototype's constructor func-
tion immediately after overwriting the prototype object:
Turtle.prototype.constructor = Turtle;
Adding multiple properties and methods at once can be made easier using a
mixin function, which is covered later in the chapter.
Overwriting Prototype Properties
An instance object can overwrite any properties or methods inherited from its prototype by
simply assigning a new value to it. For example, we can give our turtles their own weapons:
leo.weapon = "Katana Blades";
<< "Katana Blades";
Search WWH ::




Custom Search