Table of Contents
new Object() creates an object
Expand knowledge: Three other ways to create objects
Home Web Front-end JS Tutorial Let's talk about how to use the Object() function to create objects in JavaScript

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

Aug 04, 2022 pm 04:32 PM
javascript Constructor object()

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles