search
HomeWeb Front-endJS TutorialDetailed explanation of inheritance methods in JS

Detailed explanation of inheritance methods in JS

Jun 29, 2017 am 11:01 AM
javascriptExampleDetailed explanation

This article mainly introduces the detailed explanation of inheritance methods in JavaScript. This article explains the concept of js inheritance, prototypal inheritance and class inheritance, prototype chain inheritance, class inheritance, combination inheritance, prototypal inheritance, etc., which requires Friends can refer to

The concept of js inheritance

The following two inheritance methods are commonly used in js:

Prototype chain inheritance (between objects Inheritance)
Class inheritance (Inheritance between constructors)
Since js is not a truly object-oriented language like java, js is based on objects, it There is no concept of classes. Therefore, if you want to implement inheritance, you can use the prototype mechanism of js or the apply and call methods to achieve

In object-oriented languages, we use classes to create a custom object. However, everything in js is an object, so how to create a custom object? This requires the use of js prototype:

We can simply regard prototype as a template. The newly created custom objects are all copies of this template (prototype) (actually not a copy but a copy) Link, but this link is invisible. There is an invisible Proto pointer inside the newly instantiated object, pointing to the prototype object).

js can simulate the functions of the class through constructors and prototypes. In addition, the implementation of js class inheritance also relies on the prototype chain.

Prototypal inheritance and class inheritance

Class inheritance is to call the supertype constructor inside the subtype constructor.
Strict class inheritance is not very common, and is usually used in combination:

The code is as follows:

function Super(){
    this.colors=["red","blue"];
}
function Sub(){
    Super.call(this);
}


Prototypal inheritance uses existing objects Creating a new object and pointing the prototype of the subclass to the parent class is equivalent to joining the prototype chain of the parent class

Prototype chain inheritance

In order to let the subclass To inherit the attributes (including methods) of the parent class, you first need to define a constructor. Then, assign the new instance of the parent class to the constructor's prototype. The code is as follows:

The code is as follows:

<script>
    function Parent(){
        this.name = &#39;mike&#39;;
    }
    function Child(){
        this.age = 12;
    }
    Child.prototype = new Parent();//Child继承Parent,通过原型,形成链条
    var test = new Child();
    alert(test.age);
    alert(test.name);//得到被继承的属性
    //继续原型链继承
    function Brother(){   //brother构造
        this.weight = 60;
    }
    Brother.prototype = new Child();//继续原型链继承
    var brother = new Brother();
    alert(brother.name);//继承了Parent和Child,弹出mike
    alert(brother.age);//弹出12
</script>

There is still one missing link in the above prototype chain inheritance, which is Object. All constructors inherit from Object. Inheriting Object is completed automatically and does not require us to inherit manually. So what is their affiliation?

Determine the relationship between prototypes and instances

The relationship between prototypes and instances can be determined in two ways. Operator instanceof and isPrototypeof() methods:

The code is as follows:

alert(brother instanceof Object)//true
alert(test instanceof Brother);//false,test 是brother的超类
alert(brother instanceof Child);//true
alert(brother instanceof Parent);//true

As long as it is a prototype that appears in the prototype chain, it can be said to be the prototype of the instance derived from the prototype chain , therefore, the isPrototypeof() method will also return true

In js, the inherited function is called the supertype (parent class, base class is also acceptable), and the inherited function is called the subtype (subclass, Derived class). There are two main problems with using prototypal inheritance:
First, overriding the prototype with literals will break the relationship, using the prototype of the reference type, and the subtype cannot pass parameters to the supertype.

Pseudo classes solve the problem of reference sharing and the inability to pass parameters of super types. We can use the "borrowed constructor" technology

Borrowed constructor (class inheritance)

The code is as follows:

<script>
    function Parent(age){
        this.name = [&#39;mike&#39;,&#39;jack&#39;,&#39;smith&#39;];
        this.age = age;
    }
    function Child(age){
        Parent.call(this,age);
    }
    var test = new Child(21);
    alert(test.age);//21
    alert(test.name);//mike,jack,smith
    test.name.push(&#39;bill&#39;);
    alert(test.name);//mike,jack,smith,bill
</script>

Although borrowing the constructor solves the two problems just now, without a prototype, reuse is impossible, so we need a prototype chain + a borrowed constructor mode, this mode is called combined inheritance

Combined inheritance

The code is as follows:

<script>
    function Parent(age){
        this.name = [&#39;mike&#39;,&#39;jack&#39;,&#39;smith&#39;];
        this.age = age;
    }
    Parent.prototype.run = function () {
        return this.name  + &#39; are both&#39; + this.age;
    };
    function Child(age){
        Parent.call(this,age);//对象冒充,给超类型传参
    }
    Child.prototype = new Parent();//原型链继承
    var test = new Child(21);//写new Parent(21)也行
    alert(test.run());//mike,jack,smith are both21
</script>

Combined inheritance is a commonly used one An inheritance method, the idea behind it is to use the prototype chain to realize the inheritance of prototype properties and methods , and to realize the inheritance of instance properties by borrowing the constructor. In this way, function reuse is achieved by defining methods on the prototype, and each instance is guaranteed to have its own attributes.

Usage of call(): Call a method of an object and replace the current object with another object.

The code is as follows:

call([thisObj[,arg1[, arg2[, [,.argN]]]]])

Prototypal inheritance

##This kind of inheritance uses prototypes and creates new objects based on existing objects. Object without creating a custom type is called prototypal inheritance

The code is as follows:

<script>
     function obj(o){
         function F(){}
         F.prototype = o;
         return new F();
     }
    var box = {
        name : &#39;trigkit4&#39;,
        arr : [&#39;brother&#39;,&#39;sister&#39;,&#39;baba&#39;]
    };
    var b1 = obj(box);
    alert(b1.name);//trigkit4
    b1.name = &#39;mike&#39;;
    alert(b1.name);//mike
    alert(b1.arr);//brother,sister,baba
    b1.arr.push(&#39;parents&#39;);
    alert(b1.arr);//brother,sister,baba,parents
    var b2 = obj(box);
    alert(b2.name);//trigkit4
    alert(b2.arr);//brother,sister,baba,parents
</script>

Prototypal inheritance first creates a temporary constructor inside the obj() function, Then the passed in object is used as the prototype of this constructor, and finally a new instance of this temporary type is returned.

Parasitic inheritance

This inheritance method combines the prototype +

factory pattern in order to encapsulate the creation process.

The code is as follows:

<script>
    function create(o){
        var f= obj(o);
        f.run = function () {
            return this.arr;//同样,会共享引用
        };
        return f;
    }
</script>

Small problems with combined inheritance

组合式继承是js最常用的继承模式,但组合继承的超类型在使用过程中会被调用两次;一次是创建子类型的时候,另一次是在子类型构造函数的内部

 代码如下:

<script>
    function Parent(name){
        this.name = name;
        this.arr = [&#39;哥哥&#39;,&#39;妹妹&#39;,&#39;父母&#39;];
    }
    Parent.prototype.run = function () {
        return this.name;
    };
    function Child(name,age){
        Parent.call(this,age);//第二次调用
        this.age = age;
    }
    Child.prototype = new Parent();//第一次调用
</script>

以上代码是之前的组合继承,那么寄生组合继承,解决了两次调用的问题。

寄生组合式继承

代码如下:

<script>
    function obj(o){
        function F(){}
        F.prototype = o;
        return new F();
    }
    function create(parent,test){
        var f = obj(parent.prototype);//创建对象
        f.constructor = test;//增强对象
    }
    function Parent(name){
        this.name = name;
        this.arr = [&#39;brother&#39;,&#39;sister&#39;,&#39;parents&#39;];
    }
    Parent.prototype.run = function () {
        return this.name;
    };
    function Child(name,age){
        Parent.call(this,name);
        this.age =age;
    }
    inheritPrototype(Parent,Child);//通过这里实现继承
    var test = new Child(&#39;trigkit4&#39;,21);
    test.arr.push(&#39;nephew&#39;);
    alert(test.arr);//
    alert(test.run());//只共享了方法
    var test2 = new Child(&#39;jack&#39;,22);
    alert(test2.arr);//引用问题解决
</script>

call和apply

全局函数apply和call可以用来改变函数中this的指向,如下:

代码如下:

// 定义一个全局函数
    function foo() {
        console.log(this.fruit);
    }
    // 定义一个全局变量
    var fruit = "apple";
    // 自定义一个对象
    var pack = {
        fruit: "orange"
    };
    // 等价于window.foo();
    foo.apply(window);  // "apple",此时this等于window
    // 此时foo中的this === pack
    foo.apply(pack);    // "orange"

The above is the detailed content of Detailed explanation of inheritance methods in JS. 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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version