JS: Use Object.create to Emulate Constructor
here's using Object.create to emulate constructor.
// using Object.create to emulate constructor // proto object const xdad = { "a": 3 }; // constructor version const Fcon = function (x) { this.age = x; }; Fcon.prototype = xdad; // s------------------------------ // Object.Create version const Fcre = function (x) { return Object.create( xdad, { "age": { value: x, writable: true, enumerable: true, configurable: true, }, }, ); }; // s------------------------------ // test const xcon = new Fcon(32); const xcre = Fcre(32); // same parents console.assert(Reflect.getPrototypeOf(xcon) === Reflect.getPrototypeOf(xcre)); // same properties and values console.assert(JSON.stringify(Reflect.getOwnPropertyDescriptor(xcon, "age")) === JSON.stringify(Reflect.getOwnPropertyDescriptor(xcre, "age")));
JavaScript. Create object, define properties, attributes.
- JS: Object.create
- JS: Use Object.create to Emulate Constructor
- JS: Property Attributes
- JS: Enumerable Property
- JS: Property Descriptor
- JS: Object.defineProperty ❌
- JS: Reflect.defineProperty
- JS: Object.defineProperties
- JS: Object.prototype.propertyIsEnumerable ❌
- JS: Object.getOwnPropertyDescriptor ❌
- JS: Reflect.getOwnPropertyDescriptor
- JS: Object.getOwnPropertyDescriptors