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.
[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:
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, JavaScript
The 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:
- Constructor names usually start with capital letters;
- 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:
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:
- Create a new empty object
{ }
, and assign the empty object tothis
; - Perform construction The function body usually constructs the internal structure of the object through
this
; - 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);
代码的执行结果如下:
使用匿名函数当作构造函数的结果和常规构造函数没有任何区别,唯一的区别是匿名构造函数不能重复调用(因为没有名字)。这种使用方法常用在无需复用代码的场景中。
五、构造函数的返回值
常规情况下,构造函数不需要使用return
语句,它的唯一用途就是把对象的属性写入this
,然后直接默认返回this
对象就好了。
但是,由于JavaScript
对构造函数几乎没有任何约束,如果我们在一个普通函数中写了返回语句,会发生什么呢?引擎会做下面两个选择:
- 如果
return
返回的是一个对象,就返回这个对象,不再返回this
; - 如果
return
返回的是一个基础类型,则忽略返回语句,继续返回this
;
从引擎的处理方式中不难看出,构造函数的主要任务就是创建对象,处理并返回,如果使用构造函数返回一个基础类型,是没有意义的。
举个栗子:
function People(name){ this.name = name; return {name:'Nobody'};}console.log(new People('xiaoming').name);
代码执行结果如下:
可以看出,name
为’xiaoming’的对象没有被返回,而是Nobody
对象代替了xiaoming
。
如果使用return
返回一个基础类型,案例如下:
function Dog(){ this.name = 'hashiqi'; return 666;}console.log(new Dog().name);
代码执行结果如下:
可见,在返回基础类型时,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();
以上代码在构造函数中为对象添加了一个方法,代码执行结果如下:
结语
截止到目前,我们介绍的对象都只是以JavaScript
的一个特殊数据类型(数据结构)角度出发的,实际上,在面向对象领域,类才是绝对的主角。
我们会在后文逐步深入介绍JavaScript
的各种特性,包括面向对象知识,类、继承等。
总结
本文主要介绍了JavaScript
对象的构造方法和new
关键字,需要掌握并注意的点包括:
- The constructor is a regular function, but there are some conventions about capitalizing the first letter;
- The arrow function cannot be used as a constructor because it does not have
this
; - The constructor needs to be called using the
new
keyword and returns an object; - 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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
