Home>Article>Web Front-end> Constructor and new operator of JavaScript objects (detailed examples)

Constructor and new operator of JavaScript objects (detailed examples)

WBOY
WBOY forward
2022-05-10 18:16:45 2689browse

This article brings you relevant knowledge aboutjavascript, 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 thenewoperator 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 studiedC, 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 thedestructor. 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 thenewoperator;

For example:

function People(name){ this.name = name;}

ThePeoplefunction in the above code can be used as a constructor, and it is also an ordinary function. In the object'sthispointer chapter, we have introduced that ifthisis used in an ordinary function, the content ofthisdepends on the object that calls it (obj .func()), if the function is not called using an object, thenthisisWindowin non-strict mode andundefinedin 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 keywordnew.

The following code uses thenewkeyword to create twoPeopleobjects:

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 usingnewto 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 tothis;
  2. Perform construction The function body usually constructs the internal structure of the object throughthis;
  3. returns the value ofthis;

You read that right, After calling a function usingnew, the function has a return value, even if there is noreturnstatement 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 usingnewto 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 havethis;
  3. The constructor needs to be called using thenewkeyword 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.net. If there is any infringement, please contact admin@php.cn delete