JS: Object.create

By Xah Lee. Date: . Last updated: .

Object.create

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

Object.create(xParent)

Return a new empty object such that its parent is xParent.

const aa = { pp: 7 };

// create bb, with parent aa
const bb = Object.create(aa);

// bb's prototype is aa
console.assert(Reflect.getPrototypeOf(bb) === aa);
Object.create(xParent, {k1:descriptor_1, k2:descriptor_2, etc})
  • Return a new object such that its parent is xParent.
  • Also defines the new object's properties and their attributes.
  • descriptor_n are Property Descriptor.
// create a object with specific parent, properties, and property attributes

const aa = { aap: 1 };

const bb = Object.create(aa, { "bbp": { value: 2, writable: true, enumerable: true, configurable: true } });

// property aap is from object aa
console.assert(bb.aap === 1);

console.assert(bb.bbp === 2);

Example. Create object with no parent

// create a object with no parent
const xx = Object.create(null);
console.log(xx);
// [Object: null prototype] {}

Example. Create object with getter and setter

// 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

JavaScript. Object and Inheritance

JavaScript. Define Properties and attributes.