Home > Web Front-end > JS Tutorial > body text

Example introduction to JavaScript constructor and new operator

黄舟
Release: 2017-08-22 11:13:30
Original
1055 people have browsed it

This article mainly introduces the JavaScript constructor and new operator. It comprehensively introduces knowledge points through understanding the new operator, code interpretation, key analysis, the meaning of new, summary, etc. You can check the specific operation steps below. Detailed explanation, interested friends can refer to it.

Functions in JS can be either constructors or called as ordinary functions. When using new to create an object, the corresponding function is the constructor, and when called through an object, it is an ordinary function.

There are three ways to create ordinary functions: explicit declaration, anonymous definition, and new Function().

When a new object is created through new, the bottom layer of JS points the prototype chain of the new object to the prototype object of the constructor, so a prototype chain is established between the new object and the function object. The object can access the methods and properties in the prototype of the function object.

Like other high-level languages, Javascript also has constructors and new operators. We know that new is used to instantiate a class and allocate an instance object in memory. But in Javascript, everything is an object. Why do we need to use new to generate objects? This article will take you to explore the mystery of new in Javascript...

1. Get to know the new operator


function Animal(name){
this.name = name;
}
 Animal.color = "black";
 Animal.prototype.say = function(){
console.log("I'm " + this.name);
 };
 var cat = new Animal("cat");

 console.log(
 cat.name, //cat
 cat.color //undefined
 );
 cat.say(); //I'm cat

 console.log(
 Animal.name, //Animal
 Animal.color //back
 );
 Animal.say(); //Animal.say is not a function
Copy after login

2. Code interpretation

Lines 1-3 create a function Animal and define the attribute on this: name, the value of name is The formal parameters when the function is executed.

Line 4 defines a static property: color on the Animal object (Animal itself is a function object), and assigns the value "black"

Lines 5-7 are in the prototype object of the Animal function A say() method is defined on the prototype, and the say method outputs the name value of this.

Line 8 creates a new object cat through the new keyword

Line 10-14 The cat object tries to access the name and color attributes and calls the say method.

The Animal object in lines 16-20 tries to access the name and color properties and calls the say method.

3. Key analysis

The 8th line of code is the key:

var cat = new Animal( "cat");

Animal itself is an ordinary function, but when an object is created through new, Animal is the constructor.

When the JS engine executes this code, it does a lot of work internally, and uses pseudo code to simulate its workflow as follows:


new Animal("cat") = {

var obj = {};

obj.__proto__ = Animal.prototype;

var result = Animal.call(obj,"cat");

return typeof result === 'object'? result : obj;
}
Copy after login

(1)Create an empty object obj;

(2)Point the proto of obj to the prototype object prototype of the constructor Animal. At this time, the obj object is established Prototype chain: obj->Animal.prototype->Object.prototype->null

(3)Call the Animal function in the execution environment of the obj object and pass the parameter "cat" . Equivalent to var result = obj.Animal("cat").

(4)Examine the return value returned in step 3. If there is no return value or a non-object value is returned, obj will be returned as a new object; otherwise, the return value will be used as a new object The object is returned.

After understanding its operating mechanism, we know that cat is actually the return value of process (4), so we know more about the cat object:

The prototype chain of cat is :cat->Animal.prototype->Object.prototype->null<br/>

##A new attribute is added to cat: name


After analyzing the cat generation process, let’s look at the output result:

cat.name -> In process (3), the obj object generates the name attribute. Therefore, cat.name is the obj.name here

cat.color -> cat will first search for its own color. If it does not find it, it will search along the prototype chain. In the above example, we only use the Animal object color is defined on it, but it is not defined on its prototype chain, so it cannot be found.

cat.say -> cat will first search for its own say method. If it is not found, it will search along the prototype chain. In the above example, we defined say on the Animal prototype, so in the prototype chain I found the say method on .

In addition, this.name is also accessed in the say method. This here refers to its caller obj, so the value of obj.name is output.

For Animal, it is also an object itself, so it also obeys the above search rules when accessing properties and methods, so:

Animal.color -> “black”

Animal.name -> "Animal", Animal first searches for its own name and finds the name, but this name is not the name we defined, but a built-in property of the function object.

Generally, when a function object is generated, it will have a built-in name attribute and use the function name as the assignment value (only function objects).

Animal.say -> Animal does not find the say method in itself, and will also search along its prototype chain. What is the prototype chain of Animal?

From the test results: Animal's prototype chain is like this:


Animal->Function.prototype->Object.prototype->null


So there is no say method defined on Animal’s prototype chain!

4. The meaning of new’s existence

认识了new运算符之后,我们再回到开篇提到的问题:JS中万物皆对象,为什么还要通过new来产生对象?

要弄明白这个问题,我们首先要搞清楚cat和Animal的关系:

通过上面的分析,我们发现cat继承了Animal中的部分属性,因此我们可以简单的理解:Animal和cat是继承关系。

另一方面,cat是通过new产生的对象,那么cat到底是不是Animal的实例对象? 我们先来了解一下JS是如何来定义“实例对象”的?

A instanceof B
如果上述表达式为true,JS认为A是B的实例对象,我们用这个方法来判断一下cat和Animal

cat instanceof Animal; //true
从执行结果看:cat确实是Animal实例,要想证实这个结果,我们再来了解一下JS中instanceof的判断规则:


var L = A.__proto__;
var R = B.prototype;
if(L === R)
return true;
Copy after login

如果A的proto 等价于 B的prototype,就返回true

在new的执行过程(2)中,cat的proto指向了Animal的prototype,所以cat和Animal符合instanceof的判断结果。

因此,我们认为:cat 是Animal的实例对象。

5、总结

在Javascript中, 通过new可以产生原对象的一个实例对象,而这个实例对象继承了原对象的属性和方法。因此,new存在的意义在于它实现了Javascript中的继承,而不仅仅是实例化了一个对象!

The above is the detailed content of Example introduction to JavaScript constructor and new operator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template