JavaScript: Object.create

By Xah Lee. Date: . Last updated: .

The most general way to create a object is using Object.create(args). It lets you specify its parent object, and also specify the new object's properties, and each property's attributes.

Object.create(parentX)
Return a new empty object such that its parent is parentX.
Object.create(parentX, {k1:descriptor_1, k2:descriptor_2, etc})
Return a new object such that its parent is parentX. Also defines the new object's properties and their attributes. descriptor_n are Property Descriptor.

Object.create(‹parent›)

const x1 = { b: 7 };
const x2 = Object.create(x1);
console.log(Reflect.getPrototypeOf(x2) === x1);

You can write Object.create(null) to create a object that has no parent.

// create a object with no parent
const xx = Object.create(null);

Object.create(‹parent›, ‹properties_spec›)

// using Object.create to create a object with specific parents, properties, and property attributes

const x1 = { p1: 1 };

// create a object x2, with parent x1, and also with property “p2”, and also set p2's value and attributes
const x2 = Object.create(
  x1,
  { "p2": { value: 2, writable: true, enumerable: true, configurable: true } },
);

console.log(x2.p1 === 1);
console.log(x2.p2 === 2);

Create Getter/Setter Properties Example

// define getter and setter properties using Object.create

const jj = Object.create(
  Object.prototype,
  {
    "a": {
      get: function () {
        console.log("getter called");
      },
    },
    "b": {
      set: function (x) {
        console.log("setter called with arg " + x);
      },
    },
  },
);

jj.a;
// prints
// getter called

jj.b = 3;
// prints
// setter called with arg 3
BUY ΣJS JavaScript in Depth