Home > Web Front-end > JS Tutorial > body text

Let's talk about how to use the Object() function to create objects in JavaScript

青灯夜游
Release: 2022-08-04 17:55:49
forward
2152 people have browsed it

How to use the Object() function to create an object? The following article will introduce you to the method of creating objects using the Object() constructor (with three other methods of creating objects). I hope it will be helpful to you!

Let's talk about how to use the Object() function to create objects in JavaScript

new Object() creates an object


JavaScript natively provides Object objects (note that the initial O is capitalized) , all other objects inherit from this object. Object itself is also a constructor, and new objects can be generated directly through it.

The Object() function can wrap the given value into a new object.

Syntax:

new Object()
new Object(value)
Copy after login

Parameters value are optional parameters of any type.

  • If the value value is null or undefined or is 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 and an object of the type corresponding to the given value will be returned. ;

  • If the value value is a reference type, this value will still be returned.

    If the given value is an existing object, the existing value (same address) will be returned.

var obj = new Object();      //创建了一个空的对象
obj.uname = 'zhangsanfeng';
obj.name = 18;       //字面量方式创建对象不同,这里需要用 =  赋值添加属性和方法
obj.sex = 'nan';      //属性和方法后面以;结束
obj.sayHi = function() {
console.log('hi');
}
console.log(obj.uname);  
console.log(obj['age']);
Copy after login

Lets talk about how to use the Object() function to create objects in JavaScript

Description: Generate a new object by writing new Object(), with literals The writing o = {} is equivalent.

var o1 = {a: 1};
var o2 = new Object(o1);
o1 === o2 // true

new Object(123) instanceof Number
// true
Copy after login

Like other constructors, if you want to deploy a method on the Object object, there are two methods.

(1) Deployed in the Object object itself

For example, define a print method on the Object object to display the contents of other objects.

Object.print = function(o){ console.log(o) };
var o = new Object();
Object.print(o)
// Object
Copy after login

(2) Deployment in Object.prototype object

All constructors have a prototype attribute pointing to a prototype object. All properties and methods defined on the Object.prototype object will be shared by all instance objects. (For a detailed explanation of the prototype attribute, see the chapter "Object-Oriented Programming".)

Object.prototype.print = function(){ console.log(this)};
var o = new Object();
o.print() // Object
Copy after login

The above code defines a print method in Object.prototype, and then generates an Object instance o. o directly inherits the properties and methods of Object.prototype and can call them on itself. In other words, the print method of the o object essentially calls the Object.prototype.print method. .

It can be seen that although the print methods of the above two writing methods have the same function, their usage is different, so it is necessary to distinguish between "constructor method" and "instance object method".

Object()

Object itself is a function. When used as a tool method, any value can be converted into an object. This method is often used to ensure that a certain value must be an object.

  • If the parameter is a primitive type value, the Object method returns an instance of the corresponding packaging object

Object() // 返回一个空对象
Object() instanceof Object // true

Object(undefined) // 返回一个空对象
Object(undefined) instanceof Object // true

Object(null) // 返回一个空对象
Object(null) instanceof Object // true

Object(1) // 等同于 new Number(1)
Object(1) instanceof Object // true
Object(1) instanceof Number // true

Object('foo') // 等同于 new String('foo')
Object('foo') instanceof Object // true
Object('foo') instanceof String // true

Object(true) // 等同于 new Boolean(true)
Object(true) instanceof Object // true
Object(true) instanceof Boolean // true
Copy after login

The above code indicates that the Object function can convert each The value is converted into the object generated by the corresponding constructor.

  • If the parameter of the Object method is an object, it always returns the original object.

var arr = [];
Object(arr) // 返回原数组
Object(arr) === arr // true

var obj = {};
Object(obj) // 返回原对象
Object(obj) === obj // true

var fn = function () {};
Object(fn) // 返回原函数
Object(fn) === fn // true
Copy after login

Using this, you can write a function to determine whether the variable is an object.

function isObject(value) {
  return value === Object(value);
}

isObject([]) // true
isObject(true) // false
Copy after login

Expand knowledge: Three other ways to create objects

1. Object literal{ …}

The object literal method is one of the most commonly used methods. It 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 };
// ES2015中,属性名和变量名相同时可简写为:
var obj3 = { name, age };

// 扩展属性,ES2018新特性,可用于克隆或合并对象,浅拷贝,不包括原型
var obj4 = { ...obj3 };
Copy after login

2. Object.create()

##Object.create()method Creates a new object, using an existing object to provide the __proto__ of the newly created object.

/**
 * 创建一个具有指定原型的对象,并且包含指定的属性。
 * @param o 新创建对象的原型对象。可能为空
 * @param properties 包含一个或多个属性描述符的 JavaScript 对象。
 */
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;
}
Copy after login
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 } });
// 属性描述对象中省略了的属性默认为false,所以p是不可写,不可枚举,不可配置的
Object.getOwnPropertyDescriptors(obj3);	// p: {value: 42, writable: false, enumerable: false, configurable: false}

//创建一个可写的,可枚举的,可配置的属性p
var obj4 = Object.create({}, {
	p: { value: 42, writable: true, enumerable: true, configurable: true }
});

//不能同时指定访问器(get和set)和 值或可写属性
var obj4 = Object.create({}, {
	p: {
    	// value: 42,		// 不能和get set同时存在
    	// writable: true,	// 不能和get set同时存在
    	enumerable: true,
    	configurable: true,
    	get: function() { return 10 },
    	set: function(value) { console.log("Setting `p` to", value); }
  }
});
Copy after login

3. Object.assign()

##Object.assign()

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

Object.assign()

method is used to copy the values ​​of all self's enumerable properties from one or more source objects. to the target object. Return the target object.

Object.assign(target, …sources)
Copy after login

If the target object or source object has the same properties, the properties of the later object will overwrite the properties of the previous object.