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 x1 = {b:7};
const x2 = Object.create(x1); // x2 is now child of x1
console.log(Reflect.getPrototypeOf(x2) === x1); // 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 x1 = { p1: 1 };

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

console.log(x2.p1 === 1);
console.log(x2.p2 === 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