Java Reference
In-Depth Information
•
It calls the
toString()
method on both objects and they print
the same string. This is another case of inheritance. The
point
object does not set its prototype, so its prototype is, by default,
set to
Object.prototype
object, where
Object
is a built-in object
in Nashorn. The
toString()
method is defined in
Object.
prototype
and it is inherited by default by all objects. The
coloredPoint
object inherited it from the
point
object and the
point
object inherited it from the
Object.prototype
object.
Finally, it compares the prototypes of objects and prints the
•
results. The output confirms the prototype chain as discussed.
Figure
4-1
depicts the prototype chain for the
point
and
coloredPoint
objects.
Notice that the
Object.prototype
has its prototype set to
null
, indicating the end of
the prototype chain. You could have set the prototype for the
point
object to
null
, thus
eliminating the
Object.prototype
from the prototype chain.
Figure 4-1.
The Prototype Chain for the point and coloredPoint Objects
In the previous example, you saw that the two objects shared the same properties
named
x
and
y
. You do not really want to share object's states. Typically, you want
each object to have its own state. You could have solved this problem by redeclaring
the
x
and
y
properties in the
coloredPoint
object. If you set the
x
and
y
properties on
coloredObject
,
coloredObject
will get new
x
and
y
properties of its own. The following
demonstrates this:
var point = {x: 10,
y: 20,
print: function() {
printf("(%d, %d)", this.x, this.y);
}
};
var coloredPoint = {color: "red",
print: function() {
printf("(%d, %d, %s)", this.x,
this.y, this.color);
}
};
Search WWH ::
Custom Search