Home Web Front-end JS Tutorial JavaScript constructor and new operator (key points, must-read)

JavaScript constructor and new operator (key points, must-read)

May 19, 2018 am 09:25 AM
javascript js operator

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 parameter 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. Use 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 prototype chain of the obj object is established: 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

A new attribute has been added to cat: name

After analyzing the generation of cat process, let’s take a 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 Animal The say method is not defined on the prototype chain!

4. The meaning of new’s existence

After understanding the new operator, let’s return to the question mentioned at the beginning: everything in JS They are all objects, why do we need to use new to generate objects?

要弄明白这个问题,我们首先要搞清楚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中的继承,而不仅仅是实例化了一个对象!

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JS保留一位数字后移除非数字

JS DOM元素常见增删改查操作详解

JS保留两位小数输入数校验代码

The above is the detailed content of JavaScript constructor and new operator (key points, must-read). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Analysis of the meaning and usage of += operator in C language Analysis of the meaning and usage of += operator in C language Apr 03, 2024 pm 02:27 PM

The += operator is used to add the value of the left operand to the value of the right operand and assign the result to the left operand. It is suitable for numeric types and the left operand must be writable.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Mind map of Python syntax: in-depth understanding of code structure Mind map of Python syntax: in-depth understanding of code structure Feb 21, 2024 am 09:00 AM

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Python Operators: The Ultimate Guide from Newbie to Master Python Operators: The Ultimate Guide from Newbie to Master Mar 11, 2024 am 09:13 AM

Introduction to python operators Operators are special symbols or keywords used to perform operations between two or more operands. Python provides a variety of operators covering a wide range of uses, from basic mathematical operations to complex data manipulation. Mathematical operators Mathematical operators are used to perform common mathematical operations. They include: operator operation examples + addition a + b - subtraction a-b * multiplication a * b / division a / b % modulo operation (take the remainder) a % b ** power operation a ** b // integer division (discard the remainder) a//b Logical Operators Logical operators are used to concatenate Boolean values ​​and evaluate conditions. They include: operator operations examples and logical and aandbor logical or aorbnot logical not nota comparison operations

See all articles