JS: How to 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

console.log(
Object.getPrototypeOf(o1) ===
Object.getPrototypeOf(o2)
); // true

console.log(
JSON.stringify(Object.getOwnPropertyDescriptor(o1,"y")) ===
JSON.stringify(Object.getOwnPropertyDescriptor(o2,"y"))
); // true

[see JS: Property Attributes, writable, enumerable, configurable]

[see JS: Object.create]

JS Constructor/Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog