Table of Contents
Prototypal inheritance
Borrow constructor inheritance
Combined inheritance
Parasitic inheritance
Parasitic combined inheritance
Home Web Front-end JS Tutorial Sharing several js inheritance styles

Sharing several js inheritance styles

Mar 06, 2018 pm 02:36 PM
javascript share inherit

This article mainly shares with you several js inheritance styles, including prototypal inheritance, borrowed constructor inheritance, combination inheritance, parasitic style Inheritance, parasitic combination inheritance, I hope it can help everyone.

Prototypal inheritance

Inheritance can be implemented without having to define a constructor in advance. Its essence is to perform a shallow copy of a given object. The copied copy can also be further transformed

function parent(o) {
    this.username = 'father';    this.array = [1,2,3]
}function child() {
    this.age = 20}
child.prototype = new Parent();
Copy after login

Disadvantages:
1. The reference variables on the common prototype chain of the parent class and the subclass.
2. When creating a subclass instance, you cannot pass parameters to the constructor of the parent class

Borrow constructor inheritance

Borrow the constructor of the parent class to enhance the instance of the subclass, that is , which is equivalent to copying a copy of the attributes or methods of the parent class to the subclass

function Parent(name,arr) {
    this.name = name;    this.arr = arr;    this.run = function() {
        console.log('run function')
   }
}function Child(name, arr) {
    this.age = 20;
    Parent.call(this,name,arr);
}var obj1 = new Child('zhang san', [1,2,3]);var obj2 = new Child('zhang san', [1,2,3]);
obj1.arr[0] = 'hello'console.log(obj1.arr[0]); // helloconsole.log(obj2.arr[0]); // 1
Copy after login

Advantages:
1. Solve the problem of subclass instances sharing parent class reference attributes
2. Create subclasses When creating an instance, you can pass parameters to the parent class constructor.
Disadvantages:
1. Reuse cannot be achieved. Each subclass instance has a new run function. If there are too many objects in the instance, the memory consumption will be too large.

Combined inheritance

Combined inheritance avoids the shortcomings of prototype chains and borrowed constructors and combines their advantages.

function Parent(name,arr) {
    this.name = name;    this.arr = arr;
}
Parent.prototype.run = function() {
    console.log('run function');
}function Child(naem,arr) {
    this.age = '20';
    Parent.call(this,name,arr);        // 借用构造函数 ==》 核心语句   1》不能复用}
Child.prototype = new Parent(); // 原型链 ==》 核心语句  1》父构造函数不能传递参数 2》arr是引用属性,一个改变,互相影响
Copy after login

Advantages:
1. There is no problem of sharing reference attributes
2. Passable parameters
3. Methods can be reused
Disadvantages:
On the subclass prototype Right copy of the redundant attributes of the parent class instance

Parasitic inheritance

is very similar to prototypal inheritance. It also creates an object based on an object or some information, then enhances the object, and finally Return object.

function createAnother(original) {
    var clone = Object.create(original); //
    clone.sayHi = function() {
        console.log(Hi) 
   }   return clone;var Person = {
    name: 'Blob',
    friends: ['Shelby', 'Court', 'Van'];
}var anotherPerson = createAnother(person);
anotherPerson.sayHi(); // Hi
Copy after login

Parasitic combined inheritance

Combined inheritance is the most commonly used inheritance pattern in js. The biggest problem with combined inheritance is that no matter what the circumstances, the constructor will be called twice: once when creating The other time is inside the subtype constructor when prototyping a subtype.

function beget(obj){   // 生孩子函数 beget:龙beget龙,凤beget凤。
    var F = function(){};
    F.prototype = obj;    return new F();
}function Super(){
    // 只在此处声明基本属性和引用属性
    this.val = 1;    this.arr = [1];
}//  在此处声明函数Super.prototype.fun1 = function(){};
Super.prototype.fun2 = function(){};//Super.prototype.fun3...function Sub(){
    Super.call(this);   // 核心
    // ...}var proto = beget(Super.prototype); // 核心proto.constructor = Sub;            // 核心Sub.prototype = proto;              // 核心var sub = new Sub();
alert(sub.val);
alert(sub.arr);
Copy after login

Related recommendations:

Details on js inheritance

js inheritance implementation code_javascript skills

JS Inheritance--Prototype Chain Inheritance and Class Inheritance_Basic Knowledge

The above is the detailed content of Sharing several js inheritance styles. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the "Shared Members" column 】, and finally check all

Solve the problem that Discuz WeChat sharing cannot be displayed Solve the problem that Discuz WeChat sharing cannot be displayed Mar 09, 2024 pm 03:39 PM

Title: To solve the problem that Discuz WeChat shares cannot be displayed, specific code examples are needed. With the development of the mobile Internet, WeChat has become an indispensable part of people's daily lives. In website development, in order to improve user experience and expand website exposure, many websites will integrate WeChat sharing functions, allowing users to easily share website content to Moments or WeChat groups. However, sometimes when using open source forum systems such as Discuz, you will encounter the problem that WeChat shares cannot be displayed, which brings certain difficulties to the user experience.

Share two installation methods for HP printer drivers Share two installation methods for HP printer drivers Mar 13, 2024 pm 05:16 PM

HP printers are essential printing equipment in many offices. Installing the printer driver on the computer can perfectly solve problems such as the printer being unable to connect. So how to install HP printer driver? The editor below will introduce you to two HP printer driver installation methods. The first method: download the driver from the official website 1. Search the HP China official website in the search engine, and in the support column, select [Software and Drivers]. 2. Select the [Printer] category, enter your printer model in the search box, and click [Submit] to find your printer driver. 3. Select the corresponding printer according to your computer system. For win10, select the driver for win10 system. 4. After downloading successfully, find it in the folder

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

How to share Tomato novel link How to share Tomato novel link Feb 27, 2024 pm 04:20 PM

Tomato Novels is a rich treasure house of novels, which gathers a large number of high-quality novel resources. Here, you can choose your favorite novels from many different types of novels according to your preferences. For those of you who love reading, this is undoubtedly a literary world where you can fly freely. Sometimes when you encounter your favorite reading material, it’s like sharing it with friends to read together, but many users don’t know exactly how to share it, so this tutorial guide will bring you a detailed introduction to the guide, for players who want to know more Come and read along with this article! How to share Tomato novels with friends? 1. Open Tomato Novel, click to enter the novel, and click the share icon in the upper right corner. 2. Select the sharing channel. Here I take sharing to WeChat friends as an example. 3. Click Share. 4. You can check

See all articles