search
HomeWeb Front-endJS TutorialJavaScript constructor and new operator (key points, must-read)

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

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;
}

(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;

如果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
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.