Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the constructor and new operator of JavaScript object

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "JavaScript object constructor and new operator how to use", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use the constructor of JavaScript object and new operator.

Constructor and operator of 23.JavaScript object, preface

All the object creation methods mentioned above directly use the let obj = {...} syntax, as follows:

Let user = {name:'xiaoming',...}

Although such an object creation method is simple and straightforward, the code of the object cannot be reused, and the amount of code will be very high when creating many similar objects.

At this point, you need to use the constructor and the new operator to build similar objects.

Second, the constructor

If you have learned other object-oriented languages of children's shoes should be no stranger to construction methods, especially learning C++ children's shoes should be very impressive.

Concept and purpose of constructor

In other object-oriented languages, constructors are usually defined like this:

The constructor is a special member function with the same name as the class name, which is automatically called by the compiler when the class type object is created, ensuring that each data member has an appropriate initial value and is called only once in the object's life cycle.

We can simply understand that the constructor is the first of all the object's member methods to be called. It is often used to initialize the state of an object, such as the name of a person, the number of sections of a train, and so on.

The destructor corresponds to the constructor, which is one of the member methods of all objects, and the last one to be called is often the object that loses its existence value and is used to recycle object resources.

The life cycle of an object

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

Among them, the main work of the object creation phase is completed by the constructor, including object initialization, relationship connection and so on. The execution phase is mainly the call of the function of the object, which is used to cooperate with the execution of the whole project, usually completed by the ordinary function (the member function 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, the constructor of JavaScript object is special. It can be any ordinary function and does not need to be defined in the object. There are only two agreements:

The naming of the constructor usually begins with an uppercase

Constructor intelligence is executed 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 a normal function. Object this pointer section, we introduced that if the content of using this,this in an ordinary function depends on the object that calls it (obj.func ()), if you do not use the object to call the function, then this is Window in non-strict mode and undefined in strict mode.

In general, calling the constructor directly will get incorrect results, and if we want to call the function as a constructor, we need to use a new keyword new.

The following code creates two People objects using the new keyword:

Let xiaoming = new People ('xiaoming'); let xiaohong = new People (' xiaohong'); console.log (xiaoming.name); console.log (xiaohong.name)

The following is the result of the code execution:

III. New keyword

When a function is called with new, the function becomes a constructor, and the engine performs the following actions:

Create a new empty object {} and assign the empty object to this

Executes the body of the constructor, which usually constructs the internal structure of the object through this

Returns the value of this

You read it correctly, after calling a function with new, the function has a return value, even if there is no return statement when defining the function.

The code new People ('xiaoming') does something similar to this code:

Function People (name) {this = {}; / / implicitly create an empty object this.name = name; return this;// to return the created object}

So when you call the constructor with new, you get an object shaped by the constructor.

The advantage of using the new keyword is that we can write the constructor code once and then create a similar object anywhere.

For example:

Let xiaoming = new People ('xiaoming'); let xiaohong = new People (' xiaohong'); let mingming = new People ('mingming')

Imagine that if the object has hundreds of lines of code, isn't it much easier to do this than {.} way? This is the object-oriented code usage, which can greatly reduce the amount of code and improve the speed of development.

If the constructor has no arguments, we can omit the parentheses when calling:

Let xiaoming = new People;// is similar to this let xiaoming = new People (); / / equivalent to this

However, it is personally recommended not to use this feature, just to tell you that this syntax exists in the specification.

Emphasize:

Technically, any function (except the arrow function, which does not have its own this) can be used as a constructor. That is, it can be run through new, which executes the above algorithm. "uppercase" is a common convention to make it clear that a function will be run using new.

Anonymous constructor

If we only want the object to be created once, we can simplify the definition of the constructor and use new to call the anonymous function directly to create an object:

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

The execution result of the code is as follows:

The result of using an anonymous function as a constructor is no different from a regular constructor, except that the anonymous constructor cannot be called repeatedly (because there is no name). This method of use is commonly used in scenarios where there is no need to reuse code.

The return value of the constructor

Normally, the constructor does not need to use the declare statement, its only purpose is to write the properties of the object to this, and then directly return the this object by default.

But since JavaScript has few constraints on constructors, what happens if we write a return statement in an ordinary function? The engine makes the following two choices:

If return returns an object, the object is returned instead of this

If return returns a base type, ignore the return statement and continue to return this

From the way the engine handles it, it's easy to see that the main task of a constructor is to create an object, process it, and return it. It doesn't make sense to use a constructor to return a base type.

Take a chestnut:

Function People (name) {this.name = name; return {name:'Nobody'};} console.log (new People ('xiaoming') .name)

The result of code execution is as follows:

As you can see, the object whose name is' xiaoming' is not returned, but the Nobody object replaces xiaoming.

If you use return to return a base type, the case is as follows:

Function Dog () {this.name = 'hashiqi'; return 666;} console.log (new Dog () .name)

The result of code execution is as follows:

As you can see, the return statement does not take effect when the underlying type is returned.

Emphasize:

Usually the constructor of an object does not return a value, and it is not necessary for us to write a special constructor using the special handling of the return value of the constructor by the engine.

Use the constructor to add methods to the object

Not only can we add properties to the object in the constructor, but because the function of JavaScript can also assign values to variables, we can also initialize the member methods of the object with the constructor.

For example, we can add a sing method to the People object:

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

The above code adds a method to the object in the constructor, and the code execution results are as follows:

At this point, I believe that you have a deeper understanding of "how to use the constructor of JavaScript object and new operator". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report