JavaScript: Use Object.create to Emulate Constructor

By Xah Lee. Date: . Last updated: .

How to use Object.create to emulate constructor?

Here is the answer.

// using Object.create to emulate constructor

const jj = { "a": 3 };

// constructor version
const F1 = function (x) {
  this.y = x;
};
F1.prototype = jj;

// Object.Create version
const F2 = function (x) {
  return Object.create(
    jj,
    { "y": { value: x, writable: true, enumerable: true, configurable: true } },
  );
};

const x1 = new F1(4);
const x2 = F2(4);

// --------------------------------------------------
// test

// same parents
console.log(
  Reflect.getPrototypeOf(x1) === Reflect.getPrototypeOf(x2),
);

// same properties and values
console.log(
  JSON.stringify(Object.getOwnPropertyDescriptor(x1, "y")) ===
    JSON.stringify(Object.getOwnPropertyDescriptor(x2, "y")),
);
BUY
ΣJS
JavaScript in Depth