search
HomeWeb Front-endJS TutorialComparative analysis of several inheritance methods in Javascript programming_javascript skills

This article analyzes the comparison of several inheritance methods in Javascript programming with examples. Share it with everyone for your reference, the details are as follows:

Opening

In the 'strict' sense, JavaScript is not a true object-oriented language. The reason for this statement is generally that JavaScript as a weakly typed language is very different from the inheritance method of strong languages ​​​​such as Java or C#, so it is a non-mainstream object-oriented method by default, and there are even many The book describes it as a 'not fully object-oriented' language. In fact, I personally feel that the method is not important, what is important is whether it has object-oriented thinking. People who say that JavaScript is not an object-oriented language may not have studied the inheritance method of JavaScript in depth, so I wrote this article for communication.

Why you need to use javascript to implement inheritance

The performance of early PC machines is really not flattering. All the pressure was on the server side, and the client browser was purely a decoration. Coupled with the popular table layout and telephone line Internet access at that time, browsing a web page was very slow; now the Internet era is developing rapidly, personal computer hardware has been greatly improved, and the performance of client browsers is also very disappointing. The model of web development is also quietly changing: the server is no longer as "hard" as before. Instead, the browser should take on as many tasks as possible. In this way, the pressure is distributed to each client. Not only does the enterprise Saving costs also makes web front-end development more interesting - more and more front-end frameworks are emerging, and even many front-end MVC frameworks have emerged. In this context, the role of JavaScript is definitely not just to do some simple verification, send some requests or operate some DOM. It needs to play more roles like front-end routing and business layer, and JavaScript needs to do a lot of logical tasks. , which includes the abstraction of front-end data (i.e. model), and only by using object-oriented thinking can the abstracted data be processed well, so inheritance is very important here.

Start with a simple need

Now extract a model named Person from the front desk, which has basic attributes name and age. By default, everyone can speak, so the speaking function is placed on the prototype object for each instance to enjoy. Now for Man, it needs to inherit the basic attributes of Person and add its own unique attributes on this basis.

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man() {
  //my own properties
}

The following introduces several mainstream inheritance methods.

1. Prototype chain inheritance

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man() {
}
Man.prototype = new Person('pursue');
var man1 = new Man();
man1.say(); //hello, my name is pursue
var man2 = new Man();
console.log(man1.say === man2.say);//true
console.log(man1.name === man2.name);//true

This inheritance method is very direct. In order to obtain all attribute methods of Person (instance and prototype), the instance new Person('pursue') of the parent class is directly assigned to the prototype of the subclass. In fact, the subclass The class instances man1 and man2 themselves are completely empty objects. All attributes and methods have to be found on the prototype chain, so the attributes and methods found are the same.
Therefore, it is unrealistic to directly use prototype chain inheritance.

2. Use constructor inheritance

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man(name, age) {
  Person.apply(this, arguments);
}
//Man.prototype = new Person('pursue');
var man1 = new Man('joe');
var man2 = new Man('david');
console.log(man1.name === man2.name);//false
man1.say(); //say is not a function

Here the subclass uses apply in the constructor to call the constructor of the parent class, so as to achieve the effect of inheriting the properties of the parent class. It is much better than directly using the prototype chain. At least each instance has its own share. resources, but this method can only inherit the instance attributes of the parent class, so the say method cannot be found. In order to inherit all the attributes and methods of the parent class, the prototype chain must be modified, thus introducing the combined inheritance method.

3. Combination inheritance

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man(name, age) {
  Person.apply(this, arguments);
}
Man.prototype = new Person();
var man1 = new Man('joe');
var man2 = new Man('david');
console.log(man1.name === man2.name);//false
console.log(man1.say === man2.say);//true
man1.say(); //hello, my name is joe

It should be noted that the instance attributes of man1 and man2 actually override the prototype attributes, but they do not override the say method on the prototype (because they do not have it), so here man1.say === man2.say still returns true, so be careful not to override the prototype property as it is common to all instances.

4. Parasitic combination inheritance

To be honest, I really don’t know the name of the following form, but it is indeed the most popular and classic JavaScript inheritance method. In fact, you only need to understand the structure of the prototype object:

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man(name, age) {
  Person.apply(this, arguments);
}
Man.prototype = Object.create(Person.prototype);//a.
Man.prototype.constructor = Man;//b.
var man1 = new Man('pursue');
var man2 = new Man('joe');
console.log(man1.say == man2.say);
console.log(man1.name == man2.name);

In fact, the only difference between parasitic combination inheritance and the above combination inheritance is the way to construct the prototype object of the subclass (a. and b.). The Object.creat(obj) method is used here, which will process the incoming obj The object is shallow copied, similar to:

function create(obj){
  function T(){};
  T.prototype = obj;
  return new T();
}

Therefore, a. will connect the prototype object of the subclass with the prototype object of the parent class well, instead of directly copying the prototype of the subclass like the general combined inheritance (such as Man.prototype = new Person();), this is just a very violent overwriting of attributes. The parasitic combination inheritance method inherits instance attributes and prototype attributes separately, which is more reasonable in implementation.

Note: Code b. will not change the result of instanceof, but it is more rigorous for scenarios where construcor is needed.

I hope this article will be helpful to everyone in JavaScript programming.

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: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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