JS: Object.create
Object.create
The most general way to create a object. It lets you specify its parent object, and also specify the new object's properties, and each property's attributes.
Object.create(xParent)-
Return a new empty object such that its parent is xParent.
xParent is null, it creates a object without parent.
const xdad = { dog: 7 }; // create xson, with parent xdad const xson = Object.create(xdad); // xson's prototype is xdad console.assert(Reflect.getPrototypeOf(xson) === xdad); object with no parent
// create a object with no parent const xx = Object.create(null); console.log(xx); // [Object: null prototype] {} console.log( Reflect.getPrototypeOf(xx), ); // null Object.create(xParent, {k1:descriptor_1, k2:descriptor_2, etc})-
Return a new object x such that x's parent is xParent and x has specified properties and attributes.
descriptor_n are Property Descriptor.
// create a object with specific parent, properties, and property attributes const xdad = { car: 1 }; const xson = Object.create( xdad, { "toy": { value: 2, writable: true, enumerable: true, configurable: true, }, }, ); // property car is from object xdad console.assert(xson.car === 1); console.assert(xson.toy === 2);
Property attributes
The
Property Attributes
of objects created by of Object.create , is all false, by default.
Example. create object with getter and setter
// define getter and setter properties using Object.create const jj = Object.create( Object.prototype, { "dog": { get: function () { console.log("getter called"); }, }, "cat": { set: function (x) { console.log("setter called with arg " + x); }, }, }, ); jj.dog; // prints // getter called jj.cat = 3; // prints // setter called with arg 3