Home > Article > Web Front-end > Constructor 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.
[Related recommendations: javascript video tutorial, web front-end】
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.
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. .
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.
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.
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:
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:
When using new
to call a function, this function will become a constructor, and at this time, the engine will Perform the following actions:
{ }
, and assign the empty object to this
;this
; 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
关键字,需要掌握并注意的点包括:
this
;new
keyword and returns an object; [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!