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 xdad = { "a": 3 };

// constructor version
const Fcon = function (x) {
 this.age = x;
};
Fcon.prototype = xdad;

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

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

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

const xcon = new Fcon(32);
const xcre = Fcre(32);

// same parents
console.assert(Reflect.getPrototypeOf(xcon) === Reflect.getPrototypeOf(xcre));

// same properties and values
console.assert(JSON.stringify(Reflect.getOwnPropertyDescriptor(xcon, "age")) === JSON.stringify(Reflect.getOwnPropertyDescriptor(xcre, "age")));

JavaScript. Create object, define properties, attributes.