Java Reference
In-Depth Information
Using Object.create( ) Method
The Object.create() method is another way to create an object by specifying the
object's prototype and initial properties. Its syntax is:
Object.create(prototypeObject, propertiesObject)
The function returns the reference of the new object. The prototypeObject is an
object or null that is set as the prototype of the new object. The propertiesObject is
optional; it is a property descriptor that contains the initial list of properties for the new
object. The following two statements are equivalent. Both create empty object whose
prototype is Object.prototype :
var obj1 = {};
var obj2 = Object.create(Object.prototype);
The following statement creates an empty object with null as its prototype:
var obj = Object.create(null);
Listing 4-13 creates an object to represent the origin in a 2D plane. It uses Point.prototype
as the prototype of the new object. It specifies x and y properties for the object. Note
that the writable , enumerable and configurable properties are set to false by default
in a property descriptor. So, the origin2D object is nonmutable. The code also prints
the properties of the new object that proves that x and y properties are nonenumerable.
Note that the new object inherits the toString and distance properties from the Point.
prototype object.
Listing 4-13. Using Object.create() to Create an Object
// ObjectCreate.js
load("Point.js");
// Create a non-writable, non-enumerable, non-configurable
// Point to represent the origin
var origin2D = Object.create(Point.prototype, {x:{value:0}, y:{value:0}});
print("After creating:", origin2D);
// Cannot change x and y properties of origin2D.
// They are non-writable by default.
origin2D.x = 100; // No effect
origin2D.y = 100; // No effect
print("After changing x and y:", origin2D);
print("origin2D instanceof Point = " + (origin2D instanceof Point));
 
Search WWH ::




Custom Search