search
HomeWeb Front-endJS TutorialConstructor and new operator of JavaScript objects (detailed examples)

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',
    ...}

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;}

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

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;//把创建的对象返回}

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');

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

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

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

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

强调:

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

四、匿名构造函数

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

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

代码的执行结果如下:

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

代码执行结果如下:

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

代码执行结果如下:

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();

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

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
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software