Home Web Front-end JS Tutorial JavaScript prototypal inheritance constructor inheritance_javascript skills

JavaScript prototypal inheritance constructor inheritance_javascript skills

May 16, 2016 pm 06:02 PM
Constructor inherit

Last time we talked about "Basic Mechanism of JavaScript Prototypal Inheritance", this article will talk about constructor inheritance in detail.

Start with a simple example and create the People constructor that describes humans:

Copy the code The code is as follows:

function People(){
this.race = 'Stupid Human';
}

Then, create the Yellow constructor that describes the yellow race :
Copy code The code is as follows:

function Yellow(name, skin){
this.name = name;
this.skin = skin;
}

To enable Yellow to inherit the human People object, it can be simulated in JavaScript in many ways.

1. Object Masquerading

Object masquerading, simply put, is to use a constructor that defines an abstract class as a regular function to achieve pseudo-inheritance:
Copy code The code is as follows:

function Yellow(name, skin) {
this._extend = People;
this._extend();
delete this._extend; //Delete reference to People
this.name = name;
this.skin = skin;
}
/ /Instantiate yellow1
var yellow1 = new Yellow('Xiao Ming', 'Yellow Skin');
console.log(yellow1.name); //Xiao Ming
console.log(yellow1.race); //Stupid humans

In this code, add the private method _extend for Yellow. Since the function itself only exists in the form of a reference, the People method will be automatically called during execution and Yellow will be passed in. The name parameter of the constructor. The Yellow object's own properties and methods must be defined after the above process is completed and the references to external methods are cleared.

Note: Multiple inheritance can be achieved through object impersonation

2. Call/apply method

It may be simpler to implement inheritance through the call/apply method, without any tedious steps Operation:
Copy code The code is as follows:

function Yellow(name, skin) {
People.apply(this, arguments);
this.name = name;
this.skin = skin;
}
//Instantiate yellow2
var yellow2 = new Yellow(' David', 'dark skin')
console.log(yellow2.name); //David
console.log(yellow2.race); //Stupid human
here is the input of apply arguments array, you can also use new Array or literal array.

3. Prototype Chaining

The first prototype inheritance method is to point the prototype of the object to an instance of the parent class:
Copy code The code is as follows:

Yellow.prototype = new People();
Yellow.prototype.constructor = Yellow; //The initial prototype is completely cleared, so it is best to reset the constructor
var yellow3 = new Yellow('小王', '黄 Skin');
console.log(yellow3.race); // Stupid humans

The above code can be understood in reverse, the yellow3 instance itself cannot find the race attribute, and the race attribute on its prototype happens to be the race attribute of the instance of the People object.

If for the People object, its properties are written in the prototype, there is no need to instantiate, just point the prototype property of Yellow to the prototype property of People:
Copy code The code is as follows:

function People(){};
People.prototype.race = 'Stupid Humans';
Yellow.prototype = People.prototype;
Yellow.prototype.constructor = Yellow;

This does not perform instantiation operations, but only changes the pointer, which is very environmentally friendly. However, due to the reference type relationship, Yellow and People point to the same prototype object, which means that the modification to Yellow.prototype.constructor actually destroys the prototype object of People.

In this case, you can use an empty relay object to bypass the prototype of the parent class:
Copy codeThe code is as follows:

var F = function(){};
F.prototype = People.prototype;
Yellow.prototype = new F();
Yellow.prototype.constructor = Yellow;
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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks 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)

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.

Solve PHP error: problems encountered when inheriting parent class Solve PHP error: problems encountered when inheriting parent class Aug 17, 2023 pm 01:33 PM

Solving PHP errors: Problems encountered when inheriting parent classes In PHP, inheritance is an important feature of object-oriented programming. Through inheritance, we can reuse existing code and extend and improve it without modifying the original code. Although inheritance is widely used in development, sometimes you may encounter some error problems when inheriting from a parent class. This article will focus on solving common problems encountered when inheriting from a parent class and provide corresponding code examples. Question 1: The parent class is not found. During the process of inheriting the parent class, if the system does not

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.

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.

Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Aug 20, 2023 pm 10:49 PM

Inheritance is a concept that allows us to access the properties and behavior of one class from another class. The class that inherits methods and member variables is called a superclass or parent class, and the class that inherits these methods and member variables is called a subclass or subclass. In Java, we use "extends" keyword to inherit a class. In this article, we will discuss a Java program to calculate interest on fixed deposits and time deposits using inheritance. First, create these four Java files - Acnt.java − in your local machine IDE. This file will contain an abstract class ‘Acnt’ which is used to store account details like interest rate and amount. It will also have an abstract method 'calcIntrst' with parameter 'amnt' for calculating

Packaging technology and application in PHP Packaging technology and application in PHP Oct 12, 2023 pm 01:43 PM

Encapsulation technology and application encapsulation in PHP is an important concept in object-oriented programming. It refers to encapsulating data and operations on data together in order to provide a unified access interface to external programs. In PHP, encapsulation can be achieved through access control modifiers and class definitions. This article will introduce encapsulation technology in PHP and its application scenarios, and provide some specific code examples. 1. Encapsulated access control modifiers In PHP, encapsulation is mainly achieved through access control modifiers. PHP provides three access control modifiers,

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 force inheritance of proxy final class using Java? How to force inheritance of proxy final class using Java? Sep 06, 2023 pm 01:27 PM

How to force inheritance of proxy final class using Java? In Java, the final keyword is used to modify classes, methods, and variables, indicating that they cannot be inherited, overridden, or modified. However, in some cases, we may need to force inheritance of a final class to achieve specific needs. This article will discuss how to use the proxy pattern to implement such functionality. The proxy pattern is a structural design pattern that allows us to create an intermediate object (proxy object) that can control the behavior of another object (proxy object).

See all articles