Table of Contents
23.JavaScript Object constructors and operators new
1. Preface
2. Constructor
Constructor concept and purpose
The life cycle of an object
JavaScript constructor
3. New keyword
四、匿名构造函数
五、构造函数的返回值
六、利用构造函数为对象添加方法
结语
总结
Home Web Front-end JS Tutorial Constructor and new operator of JavaScript objects (detailed examples)

Constructor and new operator of JavaScript objects (detailed examples)

May 10, 2022 pm 06:16 PM
javascript

This article brings you relevant knowledge about javascript, which mainly introduces the constructor and new operator of objects. The constructor is the earliest member method of all objects to be called. Let’s take a look at the one below. I hope it will be helpful to everyone.

Constructor and new operator of JavaScript objects (detailed examples)

[Related recommendations: javascript video tutorial, web front-end

23.JavaScript Object constructors and operators new

1. Preface

The object creation methods mentioned above are all used directlylet obj = { ...} Syntax, the specific method is as follows:

let user = {
    name:'xiaoming',
    ...}
Copy after login

Although this method of object creation is simple and direct, the code of the object cannot be reused. When creating many similar objects, the amount of code will be very high.

At this time, you need to use the constructor and the new operator to construct similar objects.

2. Constructor

If you have studied other object-oriented languages, you should be familiar with the construction method, especially if you have studied C , you will be very impressed. .

Constructor concept and purpose

In other object-oriented languages, the constructor is usually defined like this:

Constructor It is a special member function with the same name as the class name. It is automatically called by the compiler when creating a class type object to ensure that each data member has an appropriate initial value and is only called once during the life cycle of the object.

We can simply understand that the constructor is the first one to be called among the member methods of all objects. Often used to initialize the state of an object, such as a person's name, the number of trains, etc.

Corresponding to the constructor is the destructor. The destructor is the last one called among the member methods of all objects. It is often used to recycle the object when the object loses its existence value. resource.

The life cycle of an object

An object can be divided into three stages from creation to recycling, as shown below:

Constructor and new operator of JavaScript objects (detailed examples)

Among them, the main work in the object creation phase is completed by the constructor, including object initialization, relationship connection, etc. The execution phase is mainly the call of object functions, used to coordinate the execution of the entire project, and is usually completed by ordinary functions (member functions of the object). The destruction phase is taken over by the destructor, which is used to clear the memory space occupied by the object and prevent memory leaks.

JavaScript constructor

Compared with other object-oriented languages, JavaScriptThe constructor of an object is special. It can be any ordinary function and does not need to be defined in the object. There are only two conventions:

  1. Constructor names usually start with capital letters;
  2. Constructor intelligence is performed by the new operator;

For example:

function People(name){
    this.name = name;}
Copy after login

The People function in the above code can be used as a constructor, and it is also an ordinary function. In the object's this pointer chapter, we have introduced that if this is used in an ordinary function, the content of this depends on the object that calls it (obj .func()), if the function is not called using an object, then this is Window in non-strict mode and undefined in strict mode.

Normally, calling the constructor directly will get incorrect results. If we want to call the function as a constructor, we need to use a new keyword new.

The following code uses the new keyword to create two People objects:

let xiaoming = new People('xiaoming');
let xiaohong = new People('xiaohong');
console.log(xiaoming.name);
console.log(xiaohong.name);
Copy after login

The following is the execution result of the code:

Constructor and new operator of JavaScript objects (detailed examples)

3. New keyword

When using new to call a function, this function will become a constructor, and at this time, the engine will Perform the following actions:

  1. Create a new empty object{ }, and assign the empty object to this;
  2. Perform construction The function body usually constructs the internal structure of the object through this;
  3. returns the value of this;

You read that right, After calling a function using new, the function has a return value, even if there is no return statement when defining the function.

Codenew People('xiaoming')What you do is probably similar to the following code:

function People(name){
    this = {};//隐式的创建一个空对象
    this.name = name;
    return this;//把创建的对象返回}
Copy after login

So after using new to call the constructor, What you get is an object shaped by the constructor.

使用new关键字的好处是,我们可以书写一次构造函数代码,然后在任意的地方创建类似的对象。

例如:

let xiaoming = new People('xiaoming');let xiaohong = new People('xiaohong');let mingming = new People('mingming');
Copy after login

想象一下,如果对象的代码有上百行,这么做是不是比{...}方式要简便很多呢?这就是面向对象中的代码服用,可以极大程度上降低代码量,提高开发速度。

如果构造函数没有参数,我们可以省略调用时的括号:

let xiaoming = new People;//类似于这样let xiaoming = new People();//等价于这样
Copy after login

但是个人推荐不要使用这种特性,仅仅是告知在规范中存在这种语法。

强调:

从技术上讲,任何函数(除了箭头函数,它没有自己的 this)都可以用作构造器。即可以通过 new 来运行,它会执行上面的算法。“首字母大写”是一个共同的约定,以明确表示一个函数将被使用 new 来运行。

四、匿名构造函数

如果我们只希望对象被创建一次,那么就可以简化构造函数的定义,使用new直接调用匿名函数,创建一个对象:

let xiaoming = new function(){
    this.name = 'xiaoming';}console.log(xiaoming.name);
Copy after login

代码的执行结果如下:

Constructor and new operator of JavaScript objects (detailed examples)

使用匿名函数当作构造函数的结果和常规构造函数没有任何区别,唯一的区别是匿名构造函数不能重复调用(因为没有名字)。这种使用方法常用在无需复用代码的场景中。

五、构造函数的返回值

常规情况下,构造函数不需要使用return语句,它的唯一用途就是把对象的属性写入this,然后直接默认返回this对象就好了。

但是,由于JavaScript对构造函数几乎没有任何约束,如果我们在一个普通函数中写了返回语句,会发生什么呢?引擎会做下面两个选择:

  1. 如果return返回的是一个对象,就返回这个对象,不再返回this
  2. 如果return返回的是一个基础类型,则忽略返回语句,继续返回this

从引擎的处理方式中不难看出,构造函数的主要任务就是创建对象,处理并返回,如果使用构造函数返回一个基础类型,是没有意义的。

举个栗子:

function People(name){
    this.name = name;
	return {name:'Nobody'};}console.log(new People('xiaoming').name);
Copy after login

代码执行结果如下:

Constructor and new operator of JavaScript objects (detailed examples)

可以看出,name为’xiaoming’的对象没有被返回,而是Nobody对象代替了xiaoming

如果使用return返回一个基础类型,案例如下:

function Dog(){
    this.name = 'hashiqi';
	return 666;}console.log(new Dog().name);
Copy after login

代码执行结果如下:

Constructor and new operator of JavaScript objects (detailed examples)

可见,在返回基础类型时,return语句是不生效的。

强调:

通常对象的构造函数没有返回值,我们也没有必要利用引擎对构造函数返回值的特殊处理,编写特别的构造函数。

六、利用构造函数为对象添加方法

在构造函数中不仅可以添加对象的属性,由于JavaScript的函数同样可以赋值给变量,我们还可以用构造函数初始化对象的成员方法。

例如,我们可以给People对象增加一个sing方法:

function People(name){
    this.name = name;
    this.sing = function(){
        console.log(`${name} is a happy boy.`);
    }}let xiaoming = new People('xiaoming');xiaoming.sing();
Copy after login

以上代码在构造函数中为对象添加了一个方法,代码执行结果如下:

Constructor and new operator of JavaScript objects (detailed examples)

结语

截止到目前,我们介绍的对象都只是以JavaScript的一个特殊数据类型(数据结构)角度出发的,实际上,在面向对象领域,类才是绝对的主角。

我们会在后文逐步深入介绍JavaScript的各种特性,包括面向对象知识,类、继承等。

总结

本文主要介绍了JavaScript对象的构造方法和new关键字,需要掌握并注意的点包括:

  1. The constructor is a regular function, but there are some conventions about capitalizing the first letter;
  2. The arrow function cannot be used as a constructor because it does not have this;
  3. The constructor needs to be called using the new keyword and returns an object;
  4. When the constructor itself has a return statement, the engine will do special processing;

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of Constructor and new operator of JavaScript objects (detailed examples). 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)

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).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles