search
HomeWeb Front-endJS TutorialJS prototype and inheritance that front-end development must know_js object-oriented

1. Prototype and constructor

All JS functions have a prototype attribute, which refers to an object, the prototype object, also referred to as the prototype. This function includes constructors and ordinary functions. We are talking more about the prototype of the constructor, but we cannot deny that ordinary functions also have prototypes. For example, an ordinary function:
Copy code The code is as follows:

function F(){
alert(F.prototype instanceof Object) //true;
}


 Constructor, that is, constructing an object. First, let’s understand the process of instantiating an object through the constructor.
Copy code The code is as follows:

function A(x){
 this.x =x;
}
var obj=new A(1);


There are three steps to instantiate the obj object:

1. Create the obj object: obj=new Object();

 2. Point the internal __proto__ of obj to the prototype of the function A that constructs it. At the same time, obj.constructor===A.prototype.constructor (This is always true, even if A.prototype no longer points to the original A prototype, that is to say: the constructor property of the instance object of the class always points to the prototype.constructor of the "constructor"), thus making obj.constructor.prototype point to A.prototype (obj.constructor.prototype===A.prototype, this is not true when A.prototype changes, as will be encountered below). obj.constructor.prototype and the internal _proto_ are two different things. _proto_ is used when instantiating an object. obj does not have a prototype attribute, but it has an internal __proto__. You can use __proto__ to obtain the prototype attributes on the prototype chain. and prototype methods, FireFox exposes __proto__, which can be alerted in FireFox (obj.__proto__);

 3. Use obj as this to call constructor A to set members (i.e. object properties and object methods) and initialized.

When these three steps are completed, the obj object has no connection with the constructor A. At this time, even if the constructor A adds any members, it will no longer affect the instantiated obj object. At this time, the obj object has the x attribute and all members of the prototype object of constructor A. Of course, the prototype object has no members at this time.

The prototype object is initially empty, that is, it does not have a member (ie prototype properties and prototype methods). You can verify how many members a prototype object has by using the following method.
Copy code The code is as follows:

var num=0;
for(o in A.prototype) {
alert(o);//alert outputs the prototype attribute name
num ;
}
alert("member: " num);//alert outputs the number of all members of the prototype .


However, once prototype properties or prototype methods are defined, all objects instantiated through the constructor inherit these prototype properties and prototype methods, which is done internally The _proto_ chain is implemented.

For example:

A.prototype.say=function(){alert("Hi")};

Then all A objects have a say method, this The say method of the prototype object is the only copy shared by everyone, rather than every object having a copy of the say method.

2. Prototype and inheritance

First, let’s look at a simple inheritance implementation.
Copy code The code is as follows:

function A(x){
 this.x =x;
}
function B(x,y){
 this.tmpObj=A;
 this.tmpObj(x);
 delete this.tmpObj;
 this. y=y;
}


Lines 5, 6, and 7: Create a temporary attribute tmpObj to reference constructor A, then execute it inside B, and delete it after execution. When this.x=x is executed inside B (this here is the object of B), B will of course have the x attribute. Of course, the x attribute of B and the x attribute of A are independent, so they are not strictly inheritance. Lines 5, 6, and 7 have a simpler implementation, which is through the call(apply) method: A.call(this,x);

Both methods pass this to the execution of A , this points to the object of B, which is why A(x) is not used directly. This inheritance method is class inheritance (js does not have classes, here it only refers to constructors). Although it inherits all the attribute methods of A's constructed object, it cannot inherit the members of A's prototype object. To achieve this goal, we need to add prototypal inheritance on this basis.


Through the following examples, you can have a deep understanding of prototypes and the perfect inheritance that prototypes participate in. (The core of this article is here^_^)
Copy code The code is as follows:

function A( x){
 this.x = x;
}
A.prototype.a = "a";
function B(x,y){
 this.y = y;
A.call(this,x);
}
B.prototype.b1 = function(){
alert("b1");
}
B.prototype = new A();
B.prototype.b2 = function(){
 alert("b2");
}
B.prototype.constructor = B;
var obj = new B (1,3);

This example is about B inheriting A. Line 7 class inheritance: A.call(this.x); As mentioned above. Prototypal inheritance is implemented in line 12: B.prototype = new A();

That means that the prototype of B points to an instance object of A. This instance object has the x attribute, which is undefined. Has an attribute with a value of "a". So the B prototype also has these two attributes (or in other words, B and A have established a prototype chain, and B is a subordinate of A). Because of the class inheritance just now, the instance object of B also has the x attribute, which means that the obj object has two x attributes with the same name. At this time, the prototype attribute x has to give way to the instance object attribute x, so obj.x is 1 , rather than undefined. Line 13 also defines the prototype method b2, so the B prototype also has b2. Although the prototype method b1 is set in lines 9 to 11, you will find that after the execution of line 12, the B prototype no longer has the b1 method, that is, obj.b1 is undefined. Because line 12 changes the B prototype pointer, the original prototype object with b1 is abandoned, and naturally there is no b1.

After line 12 is executed, B prototype (B.prototype) points to the instance object of A, and the constructor of the instance object of A is constructor A, so B.prototype.constructor is the constructor object A. (In other words, A constructs the prototype of B).

alert(B.prototype.constructor) comes out as "function A(x){...}". Similarly, obj.constructor is also an A constructor object. After alert(obj.constructor) comes out, it is "function A(x){...}", that is to say, B.prototype.constructor===obj.constructor(true) , but B.prototype===obj.constructor.prototype(false), because the former is the prototype of B and has members: x, a, b2, and the latter is the prototype of A and has members: a. How to fix this problem? On line 16, redirect the constructor of B prototype to the B constructor, then B.prototype===obj.constructor.prototype(true), all have members: x, a, b2 .

If there is no line 16, will obj = new B(1,3) call the A constructor for instantiation? The answer is no, you will find that obj.y=3, so it is still instantiated by the called B constructor. Although obj.constructor===A(true), for the behavior of new B(), the three steps mentioned above to create an instance object through the constructor are performed. The first step is to create an empty object; the second step is to create an empty object. Step, obj.__proto__ === B.prototype, B.prototype has x, a, b2 members, obj.constructor points to B.prototype.constructor, that is, constructor A; the third step, called constructor B To set and initialize members, have attributes x, y. Although not adding 16 lines does not affect the properties of obj, as mentioned in the previous paragraph, it does affect obj.constructor and obj.constructor.prototype. Therefore, after using prototypal inheritance, correction operations must be performed.

Regarding lines 12 and 16, in short, line 12 makes the prototype of B inherit all members of the prototype object of A, but also makes the prototype of the constructor of the instance object of B point to the prototype of A. So this flaw needs to be corrected through line 16.

Finished.
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
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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.

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

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools