Export (0) Print
Expand All

Object.create Function (JavaScript)

Creates an object that has the specified prototype, and that optionally contains specified properties.

Object.create(prototype, descriptors)

prototype

Required. The object to use as a prototype.

descriptors

Optional. A JavaScript object that contains one or more descriptor objects. Within the descriptors object, each descriptor object describes a data property or an accessor property.

A new object that has the specified prototype, and that optionally contains the specified properties.

A TypeError exception is thrown if any of the following conditions is true:

  • The prototype argument is not an object and is not null.

  • A descriptor in the descriptors argument has a value or writable attribute, and has a get or set attribute.

  • A descriptor in the descriptors argument has a get or set attribute that is not a function.

The optional descriptors argument is an object that contains one or more descriptor objects. Within the descriptors object, each descriptor object contains a property definition that describes the attributes of a data property or an accessor property.

A data property is a property that can store and retrieve a value. A data property descriptor contains a value attribute, a writable attribute, or both. An accessor property calls a user-provided function every time the accessor property value is set or retrieved. An accessor property descriptor contains a set attribute, a get attribute, or both. For more information, see Object.defineProperty Function (JavaScript).

To add one or more properties to an existing object, you can use the Object.defineProperties Function (JavaScript).

The following example creates an object that is a copy of another object. In the clone function, the Object.getPrototypeOf function obtains the prototype of the original object for use by the Object.create function.

function processClone() {

    // Create a constructor function and add a property
    // to its prototype.
    function Pasta(grain, width) {
        this.grain = grain;
        this.width = width;
    }
    Pasta.prototype.foodgroup = "carbohydrates";

    // Create an object from the Pasta constructor and
    // make the object non-extensible.
    var spaghetti = new Pasta("wheat", 0.2);
    Object.preventExtensions(spaghetti);

    // Copy the object and its properties.
    var newObj = clone(spaghetti);

    // Show the properties of the new object and those
    // of its prototype.
    showProperties(newObj);
    var pr = Object.getPrototypeOf(newObj);
    showProperties(pr);

    // Verify that the new object has Pasta as its prototype.
    var result = Pasta.prototype.isPrototypeOf(spaghetti);
    document.write(result + " ");

    // Verify that the new object is non-extensible.
    var result = (Object.isExtensible(newObj) === false);
    document.write(result);

    // Output:
    //  grain: wheat
    //  width: 0.2

    //  constructor: function Pasta(grain, width) { this.grain = grain; this.width = width; }
    //  foodgroup: carbohydrates

    //  true true
}


// Create an object that is a copy of another object.
function clone(oldObj) {

    // Obtain the prototype of the original object and create
    // a new object by using that prototype.
    var pr = Object.getPrototypeOf(oldObj);
    var newObj = Object.create(pr);

    // Copy the properties of the original object to the new object.
    var names = Object.getOwnPropertyNames(oldObj);
    names.forEach(
        function (prop) {
            var desc = Object.getOwnPropertyDescriptor(oldObj, prop);
            Object.defineProperty(newObj, prop, desc);
        }
    );

    // If the original object is non-extensible, make the new object

    // non-extensible.
    if (!Object.isExtensible(oldObj))
    {
        Object.preventExtensions(newObj);
    }

    // Return the new object.
    return newObj;
}

// This function is called by the processClone function.

// It is used to show the properties of the new object and
// those of its prototype.
function showProperties(obj) {
    var newLine = "<br />";

    var names = Object.getOwnPropertyNames(obj);
    names.forEach(
        function (prop) {
            document.write(prop + ": " + obj[prop]);
            document.write(newLine);
        }
    )
    document.write(newLine);
}

The following example first creates a shape object, then creates a rectangle object that has shape as the prototype, and then creates a rec object that has rectangle as the prototype.

function createShapes() {

    // Create the shape object.
    // The properties that have values of undefined are meant to be set
    // by objects that use the object as a prototype.
    var shape = { twoDimensional: true, color: undefined, hasLineSegments: undefined };

    // Freeze the object, which prevents modification of existing property
    // attributes and values, and prevents the addition of new properties.
    Object.freeze(shape);

    // Create the rectangle object, which has the shape object as
    // its prototype.
    var rectangle = Object.create(shape);

    // Set the hasLineSegments property from the shape prototype,
    // and create new properties.
    rectangle.hasLineSegments = true;
    rectangle.sides = 4;
    rectangle.width = undefined;
    rectangle.height = undefined;

    // Add a get accessor method.
    Object.defineProperty(rectangle, "area", {
        get: function () { return this.width * this.height; },
        enumerable: true,
        configurable: true
    });

    // Freeze the rectangle object.
    Object.freeze(rectangle);

    // Create an instance of a rectangle by creating an
    // object that has the rectangle object as its prototype.
    var rec = Object.create(rectangle);

    // Set the color property from the shape object prototype,
    // and set other properties from the rectangle object prototype.
    rec.color = "blue";
    rec.width = 10;
    rec.height = 5;

    // Call a method from the rectangle prototype.
    document.write(rec.area + " ");

    // Verify that the rec object exists in the prototype hierarchy
    // of the shape object.
    var result = (shape.isPrototypeOf(rec));
    document.write(result);

    // Output: 50 true
}

In the following example, the Object.create function creates an object that has an empty object as its prototype and adds a data property and an accessor property to the new object.

The descriptors object literal contains descriptor objects that are named newDataProperty and newAccessorProperty. Within each descriptor object, the enumerable property, the configurable property, and other properties describe attributes of newDataProperty and newAccessorProperty.

function addObjectWithProperties() {
    var newLine = "<br />";

    // Create an object that has an empty object as its prototype
    // and that has two new properties. The descriptors argument is
    // an object literal that includes a data property descriptor
    // and an accessor property descriptor.
    var obj = Object.create({}, {
        newDataProperty: {
            value: 101,
            writable: true,
            enumerable: true,
            configurable: true
        },
        newAccessorProperty: {
            set: function (x) {
                document.write("in property set accessor" + newLine);
                this.newaccpropvalue = x;
            },

            get: function () {
                document.write("in property get accessor" + newLine);
                return this.newaccpropvalue;
            },

            enumerable: true,
            configurable: true
        },
    });

    // Set the accessor property value.
    obj.newAccessorProperty = 10;
    document.write ("newAccessorProperty value: " + obj.newAccessorProperty + newLine);

    // Output:
    //  in property set accessor
    //  in property get accessor
    //  newAccessorProperty value: 10
}

Supported in the Internet Explorer 9 standards document mode. See Version Information.

Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards.

Community Additions

Show:
© 2014 Microsoft