Several ways of creating objects in JS

Posted by Kyrst on Wed, 12 Jan 2022 08:21:39 +0100

preface

All objects in JavaScript are from Object; All objects from Object Prototype inherits methods and properties, which of course may be overridden. This article mainly introduces several methods of creating objects.

1. Object literal {...}

Object literal is one of the most commonly used methods, which uses curly braces containing attributes {...} Quickly create objects.

var obj1 = {};
obj1.name = "Tom";

var obj2 = { name: "Tom", age: 12 };

var name = "Tom", age = 12;
var obj3 = { name: name, age: age };
// In ES2015, the attribute name and variable name are the same, which can be abbreviated as:
var obj3 = { name, age };

// Extended attributes, a new feature of ES2018, can be used to clone or merge objects, shallow copies, excluding prototypes
var obj4 = { ...obj3 };

Object properties created in literal form are writable, enumerable and configurable by default

The prototype of the object defaults to object prototype. By defining attributes__ proto__ (only attribute definitions marked with colons can be used) to change the prototype. Only when the given value is object or null, the prototype of the object will be set to the given value, otherwise the prototype will not change.

var obj1 = {};
Object.getPrototypeOf(obj1) === Object.prototype;	// true

var obj2 = { __proto__: null };
Object.getPrototypeOf(obj2) === null;				// true

var __proto__= {};
var obj3 = { "__proto__": __proto__ };
Object.getPrototypeOf(obj3) === __proto__;			// true
// Property definitions that do not use colons do not change the prototype of the object, but the name is__ proto__ Common properties of
var obj4 = { __proto__ };
Object.getPrototypeOf(obj4) === __proto__;			// false
obj4.hasOwnProperty("__proto__");					// true
Object.getPrototypeOf(obj4) === Object.prototype;	// true

var obj5 = { __proto__: "not an object or null" };
obj5.hasOwnProperty("__proto__");					// false
Object.getPrototypeOf(obj5) === Object.prototype;	// true

2. new Object()

new Object([value])

The parameter value is an optional parameter of any type.

  • If the value value is null or undefined or not passed, an empty object will be created and returned;
  • If the value value is a basic type, the object of its wrapper class will be constructed;
  • If the value value is a reference type, this value is still returned.
var obj1 = new Object();			// {}
var obj2 = new Object(undefined);	// {}
var obj3 = new Object(null);		// {}

// Basic type, construct its wrapper class object
var obj4 = new Object("Tom");		// String {"Tom"}, equivalent to new String("Tom");
Object.getPrototypeOf(obj) === String.prototype;	// true

var arr = [1, 2];
var obj5 = new Object(arr);
obj5 === arr;						// true

var obj6 = { name: "Tom", age: 12 };
var obj7 = new Object(obj6);
obj7 === obj6;						// true

3. Object.create()

Object. The create () method creates a new object and uses the existing object to provide the name of the newly created object__ proto__.

/**
 * Creates an object with the specified prototype and contains the specified properties.
 * @param o The prototype object of the newly created object. May be empty
 * @param properties A JavaScript object that contains one or more property descriptors.
 */
create(o: object | null, properties?: PropertyDescriptorMap): any;

interface PropertyDescriptorMap {
    [s: string]: PropertyDescriptor;
}

interface PropertyDescriptor {
    configurable?: boolean;
    enumerable?: boolean;
    value?: any;
    writable?: boolean;
    get?(): any;
    set?(v: any): void;
}
var obj1 = Object.create(null);
Object.getPrototypeOf(obj1) === null;	// true

var proto= {};
var obj2 = Object.create(proto);
Object.getPrototypeOf(obj2) === proto;	// true

var obj3 = Object.create({}, { p: { value: 42 } });
// The attribute omitted from the attribute description object is false by default, so p is not writable, enumerable and configurable
Object.getOwnPropertyDescriptors(obj3);	// p: {value: 42, writable: false, enumerable: false, configurable: false}

//Create a writable, enumerable, and configurable Property p
var obj4 = Object.create({}, {
	p: { value: 42, writable: true, enumerable: true, configurable: true }
});

//Accessors (get and set) and values or writable properties cannot be specified at the same time
var obj4 = Object.create({}, {
	p: {
    	// value: 42, 		//  Cannot exist with get set
    	// writable: true, 	//  Cannot exist with get set
    	enumerable: true,
    	configurable: true,
    	get: function() { return 10 },
    	set: function(value) { console.log("Setting `p` to", value); }
  }
});

Use object Create() implements class inheritance

// Parent class
function Shape() {
  this.x = 0;
  this.y = 0;
}
// Subclass
function Rectangle() {
  Shape.call(this); // Call the constructor of the parent class
}
// The prototype object of the parent class is used as the prototype object of the child class prototype. Subclass inherits parent class
Rectangle.prototype = Object.create(Shape.prototype);
// Set the constructor of the subclass prototype
Rectangle.prototype.constructor = Rectangle;

var r = new Rectangle();
r instanceof Rectangle;	// true
r instanceof Shape;		// true

4. Object.assign()

Object. The assign () method is not directly used to create objects, but it can achieve the effect of creating objects, so it is also used as a way to create objects here.

Object. The assign () method is used to copy the values of all its own enumerable properties from one or more source objects to the target object. Returns the target object.

Object.assign(target, ...sources)

  • If the target object or source object has the same properties, the properties of the subsequent object override the properties of the previous object.
  • Only the enumerable properties of the source object itself are copied to the target object. Do not process objects on the source object prototype.
  • This method uses the Get of the source object and the Set of the target object to Get and Set the value.
var o1 = { name: "Tom" };
var o2 = { name: "Jerry" };
var o3 = Object.create(o2, { 	// o2 is the prototype of o3, and name: "Jerry" is the attribute on the prototype
	a: { value: 42 }, 			// countless
	b: { value: 42, writable: false, enumerable: true, configurable: false }, 
  	c: { enumerable: true, get: function() { return 10; } } 
});
var obj1 = Object.assign(o1, o2);
obj1 === o1;		// true
obj1;				// {name: "Tom", b: 42, c: 10}
Object.getOwnPropertyDescriptors(obj1);	// Properties will not be copied
/* 	b: {value: 42, writable: true, enumerable: true, configurable: true}
	c: {value: 10, writable: true, enumerable: true, configurable: true}
	name: {value: "Tom", writable: true, enumerable: true, configurable: true} */

var o4 = { a: "a", b: { name: "Tom", age: 18 } };
var obj2 = Object.assign({}, o4);
obj2.b === o4.b;	// true, shallow copy. If the source value is a reference to an object, it will only copy its reference value.

// Merge objects, and the following attributes overwrite the previous attributes
var o1 = { a: 1, b: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { a: 3 };
var obj3 = Object.assign({}, o1, o2, o3);
obj3; 			// {a: 3, b: 2, c: 2}

// The basic type is converted to a wrapper object, and only the wrapper object of a string has its own enumerable properties.
var obj4 = Object.assign({}, "abc", null, true, undefined, 10, Symbol("foo"));
obj4;		// {0: "a", 1: "b", 2: "c"}

// If an exception occurs during copying, subsequent copying tasks will be terminated and the copied data will be retained
var t = Object.create( {}, { b: { value: 42, writable: false } }); 	// b is a read-only attribute
Object.assign(t, {a: 1}, {a: 2, b: 2, c: 3}, {c: 4});	// Cannot assign to read only property 'b' of object '#<Object>'
t;		// {a: 2, b: 42}

Topics: Javascript TypeScript object