Java Reference
In-Depth Information
Object.setPrototypeOf(coloredPoint, point);
// Call the print() methods of both objects
point.print();
coloredPoint.print();
// Change the x and y values in the point object
point.x = 100;
point.y = 200;
// Add own x and y properties to the coloredPoint object
coloredPoint.x = 300;
coloredPoint.y = 400;
// Call the print() methods of both objects
point.print();
coloredPoint.print();
(10, 20)
(10, 20, red)
(100, 200)
(300, 400, red)
the prototype chain is searched when reading the object's property, not when
updating them. recall that updating a property that does not exists adds a new property to
the object on which the property is set.
Tip
In the previous example, you saw how the prototype inheritance chain works in
Nashorn. You created objects using the object literals and set up object's prototype
using the Object.setPrototypeOf() function. You can also do the same, though a bit
differently, using function constructors. A function in Nashorn is also an object and, by
default, the prototype of a function is set to Function.prototype object. The Function.
prototype has Object.prototype as its prototype. Function.prototype contains several
useful methods and properties that can be used with all functions. For example, it
overrides the toString() method of the Object.prototype and the method prints the
source code for the function. The following code demonstrates this:
// Create a function object called log
function log(str) {
print(new Date() + ": " + str);
}
 
 
Search WWH ::




Custom Search