JavaScript: Use Object.create to Emulate Constructor

By Xah Lee. Date: . Last updated: .

How to use Object.create to emulate constructor?

Here's the answer.

// using Object.create to emulate constructor

const dad = {"a":3};

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

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

const o1 = new F1(4);
const o2 = F2(4);

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

// same parents
console.log(
Reflect.getPrototypeOf(o1) === Reflect.getPrototypeOf(o2)
); // true

// same properties and values
console.log(
JSON.stringify(Object.getOwnPropertyDescriptor(o1,"y")) === JSON.stringify(Object.getOwnPropertyDescriptor(o2,"y"))
); // true
JS in Depth
XAH  BUY NOW