JavaScript: 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

You need to provide true values to the properties attributes, because they default to false.

〔►see JavaScript: Property Attributes

〔►see JavaScript: Object.create

JS Constructor Topic

  1. JavaScript: Keyword “this”
  2. JavaScript: What's Constructor?
  3. JavaScript: Property Key "prototype"
  4. JavaScript: Operator “new”
  5. JavaScript “instanceof” Operator
  6. JavaScript: How to Use Object.create() to Emulate Constructor?
  7. JavaScript: Property Key "constructor"
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.