JS: Use Object.create to Emulate Constructor

By Xah Lee. Date: . Last updated: .

here's using Object.create to emulate constructor.

// using Object.create to emulate constructor

// proto object
const food = { "a": 3 };

// constructor version
const Burger = function (x) {
 this.meat = x;
};
Burger.prototype = food;

// s------------------------------

// Object.create version
const Pizza = function (x) {
 const xresult = Object.create(food);
 xresult["meat"] = x;
 return xresult;
};

// s------------------------------
// test

const xburg = new Burger(32);
const xpiz = Pizza(32);

// same parents
console.assert(
 Reflect.getPrototypeOf(xburg) === Reflect.getPrototypeOf(xpiz),
);

// same properties and values
console.assert(
 JSON.stringify(
  Reflect.getOwnPropertyDescriptor(xburg, "meat"),
 ) ===
  JSON.stringify(
   Reflect.getOwnPropertyDescriptor(xpiz, "meat"),
  ),
);