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

var dad = {"a":3};

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

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

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

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

    Object.getPrototypeOf(o1) ===
); // true

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

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

[see JS: Object.create]

JS Constructor Topic

  1. JS: “this” Binding
  2. JS: What's Constructor?
  3. JS: Property Key "prototype"
  4. JS: Operator “new”
  5. JS: “instanceof” Operator
  6. JS: The Property Key Named "constructor"
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon