search
HomeWeb Front-endJS TutorialWhat are the inheritance methods in javascript

What are the inheritance methods in javascript

Jul 12, 2021 pm 01:50 PM
javascriptinherit

The inheritance methods in JavaScript include prototype chain inheritance, borrowed constructor inheritance, combined inheritance, prototype inheritance, parasitic inheritance and parasitic combined inheritance. Among them, combined inheritance is the most commonly used inheritance method.

What are the inheritance methods in javascript

#The operating environment of this article: windows10 system, javascript 1.8.5, thinkpad t480 computer.

If we want to inherit in javascript, we must first provide a parent class. We use Person as the parent class here.

All the constructor names below have no actual meaning, such as Coder, Rocker, etc., they are only used as examples

		 function Person(name){//给构造函数添加了参数
		            this.name=name;
		            this.sex="male";
		            this.say=function(){
		                console.log(this.name);
		            }
		        }
		Person.prototype.age=21;//给构造函数添加了原型属性

1. Prototype chain inheritance

		function Programmer(){
            this.name="Jayee";
        }

        Programmer.prototype=new Person();//子类构造函数.prototype=父类实例

        var per1=new Programmer();
        console.log(per1);//Programmer {name: "Jayee"}
        console.log(per1.sex);//male
        console.log(per1.age);//21
        console.log(per1 instanceof Person);//true

Key point: Make the prototype of the new instance equal to the instance of the parent class. Programmer.prototype=new Person();

Features: The attributes that an instance can inherit include: the attributes of the instance's constructor, the attributes of the parent class constructor, and the attributes of the parent class prototype. (The new instance will not inherit the attributes of the parent class instance!)

Disadvantages: 1. The new instance cannot pass parameters to the parent class constructor.

 2. Single inheritance.

 3. All new instances will share the attributes of the parent class instance. (The attributes on the prototype are shared. If one instance modification

changes the attributes of the prototype (per1.__proto__.sex="female", then per2.sex will also become female), and the other

 The prototype properties of an instance will also be modified!)

2. Borrowing constructor inheritance

        //借用构造函数继承
        function Coder(){
            Person.call(this,"Jayee");//重点:借用了Person
            this.age=18;
        }
        var cod1=new Coder();
        console.log(cod1);
        //Coder {name: "Jayee", sex: "male", hobby: "", age: 18, say: ƒ}
        console.log(cod1.name);//Jayee
        console.log(cod1.age);//18
        console.log(cod1 instanceof Person);//false

Key points: Use .call() and .apply() to introduce the parent class constructor Subclass function (self-execution (copying) of the parent class function in the subclass function)

Features: 1. Only inherits the attributes of the parent class constructor and does not inherit the attributes of the parent class prototype. (It can be seen from

that cod1.age is 18 instead of 21)

2. Solved the shortcomings 1, 2, and 3 of prototype chain inheritance.

 3. You can inherit multiple constructor attributes (call multiple).

 4. Parameters can be passed to the parent instance in the child instance.

Disadvantages: 1. Only the attributes of the parent class constructor can be inherited.

 2. The reuse of constructors cannot be achieved. (You have to call it again every time you use it)

3. Each new instance has a copy of the parent class constructor, which is bloated.

3. Combined inheritance (combined prototype chain inheritance and borrowed constructor inheritance) (commonly used)

        //组合继承
        function Typer(name){
            Person.call(this,name);
        }
        Typer.prototype=new Person();
        var typ=new Typer("Jayee");
        console.log(typ);
        //Typer {name: "Jayee", sex: "male", hobby: "", say: ƒ}
        console.log(typ.name);//Jayee,继承了构造函数
        console.log(typ.age);//21,继承了父类的原型的属性

Key point: combines the advantages of the two modes, parameter passing and reuse

Features: 1. It can inherit the attributes of the parent class prototype, pass parameters, and be reused.
 2. The constructor attributes introduced by each new instance are private.

Disadvantages: The parent class constructor is called twice (memory consumption), and the subclass constructor will replace the
parent class constructor on the prototype

4. Prototype Inheritance

        //原型式继承
        function Rocker(obj) {
        //先封装一个函数容器,用来输出对象和承载继承的原型
            function F(){}
            F.prototype=obj;//继承了传入的函数
            return new F();//返回函数对象
        }
        var per=new Person();//拿到父类实例
        var roc =Rocker(per);//F {}
        console.log(per.__proto__);//{age: 21, constructor: ƒ}
        console.log(roc.age);//21,继承了父类函数的属性

Key point: wrap an object with a function, and then return the call of this function. This function becomes an instance or object that can

add attributes at will. object.create() is this principle.

Features: Similar to copying an object and wrapping it with a function.

Disadvantages: 1. All instances will inherit the attributes on the prototype.

 2. Unable to achieve reuse. (New instance attributes are added later)

5. Parasitic inheritance

        //寄生式继承
        function Rocker(obj){
            function F(){}
            F.prototype=obj;//继承了传入的函数
            return new F();//返回函数对象
        }
        var per4=new Person();
        //以上是原型式继承,给原型式继承再套个壳子传递参数
        function Artist(obj){
            var roc=Rocker(obj);
            roc.name="Jayee";
            return roc;
        }
        var art = Artist(per4)
        //这个函数经过声明之后就成了可增添属性的对象
        console.log(typeof Artist);//function
        console.log(typeof art);//object
        console.log(art.name);//Jayee,返回了个roc对象,继承了roc的属性

The key point: It is to put a shell on the prototypal inheritance.

Advantages: No custom type is created, because it is just a shell to return the object (this), and this function naturally becomes the new object created.

Disadvantages: No prototype is used and cannot be reused.

6. Parasitic combined inheritance (commonly used)

Parasite: Return the object within the function and then call

Composition: 1. The prototype of the function is equal to another instance. 2. Use apply or call to introduce another constructor in the function, and you can pass parameters

         //寄生式组合式继承

         //寄生
         function Rocker(obj){
            function F(){}
            F.prototype=obj;//继承了传入的函数
            return new F();//返回函数对象
        }
        //Rocker就是F实例的另一种表示法
        var roc=new Rocker(Person.prototype);
        //roc实例(F实例)的原型继承了父类函数的原型
        //上述更像是原型链继承,只不过继承了原型属性

        //组合
        function Sub(){
            Person.call(this);
            //这个继承了父类构造函数的属性
            //解决了组合式两次调用构造函数属性的缺点
        }
        //重点
        Sub.prototype=roc;//继承了roc实例
        roc.constructor=Sub;//一定要修复实例
        var sub1=new Sub();
        //Sub的实例就继承了构造函数属性,父类实例,roc的函数属性
        console.log(sub1.age);//21

Key points: Fixed the problem of combined inheritance

7. Class and extends in ES6

//todo

Related video tutorial sharing: javascript video tutorial

The above is the detailed content of What are the inheritance methods in javascript. 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: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.