Object constructors are used to engender categorical types of objects for preparing the object for use and by arguments constructor can use to set the values of properties and methods when the object is first created.
Object Creation:
Create the new empty Object:
let newObject = {}; // or let newObject = Object.create( Object.prototype ); // or // Creates an object wrapper for a specific value, or // where no value is passed, // it will create an empty object and return it. let newObject = new Object();
Set properties to an object:
// 1. Dot syntax // Set properties newObject.KEY = "Art has no rules."; // Get properties let value = newObject.KEY;
// 2. Square bracket syntax // Set properties newObject["KEY"] = "Art has no rules.";
// Get properties let value = newObject["KEY"];
// 3. Object.defineProperty // Set properties Object.defineProperty( newObject, "KEY", {
value: "Art has no rules.", writable: true, enumerable: true, configurable: true }); // Or let defineProp = function ( obj, key, value ){ let config = { value: value, writable: true, enumerable: true, configurable: true }; Object.defineProperty( obj, key, config ); }; // Now lets create a new empty "person" object let person = Object.create( Object.prototype ); // Set properties to the "person" object defineProp( person, "scientist", "Albert Einstein" ); defineProp( person, "dateOfBirth", "1879" ); defineProp( person, "died", "1955" ); console.log(person); // Outputs: Object {scientist: "Albert Einstein", dateOfBirth: "1879", died: "1955"} // 4. Object.defineProperties to set multiple key & value // Set properties
Object.defineProperties( newObject, { "KEY": {
value: "First rule no rules.", writable: true }, "ANOTHERKEY": {
value: "Art has no rules.",
writable: false } }); // Es6 // 5. Classes
// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)
class ClassName { constructor(VALUE) { this.KEY = VALUE; } } // Or // With class name let NewObject = class ClassName { constructor(VALUE) { this.KEY = VALUE; } } // Or // Without class name let NewObject = class { constructor(VALUE) { this.KEY = VALUE; } }
Comments
Post a Comment