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
2294 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.
  • Only the source object's own enumerable properties will be copied to the target object. No processing is done on the object on the prototype of the source object.
  • This method uses the source object's
  • Get
  • and the target object's Set to get and set the value.
    var o1 = { name: "Tom" };
    var o2 = { name: "Jerry" };
    var o3 = Object.create(o2, { 	// o2是o3的原型,name: "Jerry"是原型上的属性
    	a: { value: 42 }, 			// 不可枚举
    	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);	// 不会拷贝属性的
    /* 	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, 浅拷贝,如果源值是一个对象的引用,它仅仅会复制其引用值。
    
    // 合并对象,后面属性覆盖前面属性
    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}
    
    // 基本类型会被转为包装对象,只有字符串的包装对象有自身可枚举属性。
    var obj4 = Object.assign({}, "abc", null, true, undefined, 10, Symbol("foo"));
    obj4;		// {0: "a", 1: "b", 2: "c"}
    
    // 拷贝过程中发生异常,会终止后续拷贝任务,已拷贝的数据保留
    var t = Object.create( {}, { b: { value: 42, writable: false } }); 	// b是只读属性
    Object.assign(t, {a: 1}, {a: 2, b: 2, c: 3}, {c: 4});	// Cannot assign to read only property &#39;b&#39; of object &#39;#<Object>&#39;
    t;		// {a: 2, b: 42}
    Copy after login
    【Related recommendations: javascript learning tutorial

    The above is the detailed content of Let's talk about how to use the Object() function to create objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template