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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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.

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 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.

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

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

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.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

How to share ppt How to share ppt Mar 20, 2024 pm 07:51 PM

People in the workplace will be familiar with PPT production, because whether it is a year-end summary or a work report, many companies require it to be presented in the form of PPT. At this time, I encountered a problem, that is, how to share PPT? Don’t worry, the editor below will show you how to share PPT. 1. First select the edited PPT and click Save in the upper left corner (if you are using WPS, you can click Login first). 2. Then click the share icon in the menu bar as shown below. 3. Then the sharing interface as shown below will pop up. You can see that a sharing link will appear. Click to send the link to share. 4. You can also click "Allow friends to edit" in the lower left corner of the picture below, so that friends can also click to edit this PPT. 5. If necessary, give P

See all articles