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(parentX)
-
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.
Example. Object.create(‹parent›)
const aa = { b: 7 }; const bb = Object.create(aa); console.log(Reflect.getPrototypeOf(bb) === aa);
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);
Example. Object.create(‹parent›, ‹properties_spec›)
// using Object.create to create a object with specific parents, properties, and property attributes const aa = { p1: 1 }; // create a object bb, with parent aa, and also with property “p2”, and also set p2's value and attributes const bb = Object.create( aa, { "p2": { value: 2, writable: true, enumerable: true, configurable: true } }, ); console.log(bb.p1 === 1); console.log(bb.p2 === 2);
Example. Create Getter/Setter Properties
// define getter and setter properties using Object.create const jj = Object.create( Object.prototype, { "a": { get: function () { console.log("getter called"); }, }, "b": { set: function (x) { console.log("setter called with arg " + x); }, }, }, ); jj.a; // prints // getter called jj.b = 3; // prints // setter called with arg 3
JavaScript. Object and Inheritance
- JS: Object Tutorial
- JS: Object Overview
- JS: Object Type
- JS: Test is Object Type 📜
- JS: Determine Type of Object
- JS: Prototype and Inheritance
- JS: Prototype Chain
- JS: Object.prototype.isPrototypeOf
- JS: Get Set Prototype
- JS: Show Prototype Chain 📜
- JS: Prototype Tree
- JS: Dot Notation and Prototype Chain
- JS: Create Object
- JS: Object Literal Expression
- JS: Object.create
- JS: Object Literal Expression vs Object.Create
- JS: Create Object with Parent X
- JS: Prevent Adding Property
- JS: Deep Copy Array or Object 📜
- JS: Test Equality of Array and Object by Content 📜
- JS: Add Method to Prototype
- JS: Object (class)
- JS: Object Constructor
- JS: Object.prototype