JavaScript: Object.create

By Xah Lee. Date: . Last updated: .

The most general way to create a object is using Object.create(). It lets you specify its parent object, and also specify the new object's properties, and each property's attributes.

Return a new empty object such that its parent is parentX.
Object.create(parentX, {k1:descriptor_1, k2:descriptor_2 etc})
Return a new object such that its parent is parentX. Also defines the new object's properties and their attributes. descriptor_n are Property Descriptor.


const o1 = {b:7};
const o2 = Object.create(o1); // o2 is now child of o1
console.log(Reflect.getPrototypeOf(o2) === o1); // true

You can write Object.create(null) to create a object that has no parent.

// create a object with no parent
const xx = Object.create(null);

Object.create(‹parent›, ‹properties_spec›)

// using Object.create() to create a object with specific parents, properties, and property attributes

const o1 = { p1: 1 };

// create a object o2, with parent o1, and also with property “p2”, and also set p2's value and attributes
const o2 = Object.create(
  { "p2": { value: 2, writable: true, enumerable: true, configurable: true } },

console.log(o2["p1"]); // prints 1
console.log(o2["p2"]); // prints 2

Create Getter/Setter Properties Example

// define getter and setter properties using Object.create

const obj = Object.create (
"a": { get : function () { console.log( "getter called" ) } },
"b": { set : function (x) { console.log( "setter called with arg "+x ) }}

// prints
// getter called

obj.b = 3;
// prints
// setter called with arg 3

Use Object.create to Emulate Constructor

Use Object.create to Emulate Constructor

JavaScript in Depth

JS Obj Reference

Object Object