Home Web Front-end JS Tutorial Alibaba technical articles share the implementation of Javascript inheritance mechanism_javascript skills

Alibaba technical articles share the implementation of Javascript inheritance mechanism_javascript skills

May 16, 2016 pm 03:20 PM
javascript inheritance mechanism

As a scripting language, Javascript was not designed with object-oriented features in mind. Even in this era of modern browsers and various Javascript frameworks/libraries mushrooming like mushrooms after a rain, there is not even a class keyword in Javascript. If you want to write a class, you have to use function. As for inheritance, overloading, etc., don't expect it.

But, how can we live without inheritance? Should we copy all the common logic to achieve the lowest level of code reuse?

The answer is of course - NO, so we have to implement inheritance ourselves!

Goal

The most critical goal is of course inheritance - the subclass automatically has all the public properties and methods of the parent class.

Support instanceof, for example, c is an instance of a subclass, and P is a parent class, c instanceof P should return true.

Secondly, you should be able to override (Override) the methods of the parent class, and in the methods of the subclass, you can easily call the method of the same name of the parent class.

As for overloading, it cannot be implemented due to the language characteristics of Javascript (methods cannot have the same name, even if their parameter lists are different).

Design and Implementation

Javascript objects have a very important attribute - __proto__, which is the prototype. A prototype is essentially an object, so it can also have its own prototype, thus forming a prototype chain. When you call a method of an object or read a property of the object, the Javascript executor does this:

1. First look for the corresponding method or attribute in the object. If it cannot be found,
2. Find the prototype of the object. If you still can’t find it,
3. Find
in the prototype’s prototype 4....
5. Until the prototype of Object is finally found, if not yet, return undefined
As shown below:


This feature of the prototype chain is very similar to inheritance, so naturally, we can use it to implement the inheritance mechanism. The prototype chain's support for instanceof makes it a good choice.

We define the extend function. This function accepts two parameters, the first is the parent class, and the second is the subclass, as shown below:

function extend(ParentClass, ChildClass) {
  ...
  return ChildClass;
}
Copy after login

This function processes the subclass and returns the subclass. The processing logic is as follows:

Establish a prototype chain

By connecting the prototype chain of the subclass to the prototype chain of the parent class, the subclass can automatically have the methods and properties of the parent class:

var pp = ParentClass.prototype,
  cp = ChildClass.prototype;
function T() {};
T.prototype = pp;
ChildClass.prototype = new T();
Copy after login

In order to connect the prototype chain, you need to create an instance of the parent class and assign it to the prototype property of the child class. But we don't want to instantiate the parent class in the extend method, so we introduce an intermediate class T to solve this problem.

Implement rewriting

After the prototype chain is established, we also need to retain the methods and attributes on the original subclass prototype:

Method

If the parent class has a method with the same name, we use a closure to retain references to the parent class method and the child class method. Then, modify the reference to the method in the new prototype to point to a new function. In this function, we create a temporary attribute super, point it to the parent class method, and call the subclass method, so that in the subclass method, the parent class method can be called through this.super:

ChildClass.prototype[name] = (function(pm, cm) {
  return function() {
    var _super = this.super;
    this.super = pm;
    var result = cm.apply(this, arguments);
    this.super = _super;
    return result;
  };
})(pp[name], cp[name]);
Copy after login

Attributes

For attributes, there is no problem of overwriting, so just add the attributes in the original prototype of the subclass to the new prototype:

ChildClass.prototype[name] = cp[name];
Copy after login

Constructor

In order to allow the subclass to access the constructor of the parent class, we assign the parent class to the super attribute of the subclass:

ChildClass.super = ParentClass;
Copy after login

How to use

Suppose we want to design a management system that involves customers, workers, managers, etc. By abstracting the commonalities between customers and employees, we get People; then by abstracting the commonalities between workers and managers, we get Employee. In this way we get the three-level class structure:


The code to implement this design is as follows:

function People(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
}

function Employee(firstname, lastname, company) {
  Employee.super.apply(this, arguments);
  this.company = company;
}

function Manager(firstname, lastname, company, title) {
  Manager.super.apply(this, arguments);
  this.title = title;
}

Copy after login

We want to have a description for each person. People is the name; employees include the company name after the name; and manager includes the position after the employee's description. The code is as follows:

People.prototype.summary = function() {
  return this.firstname + " " + this.lastname;
};

Employee.prototype.summary = function() {
  return this.super.call(this) + ", " + this.company;
};

Manager.prototype.summary = function() {
  return this.super.call(this) + ", " + this.title;
};

Copy after login

After all member methods have been defined, declare the inheritance of the class (you must define the method first, and then declare the inheritance of the class, otherwise you cannot use this.super in the method to call the parent class method!):

extend(People, Employee);
extend(Employee, Manager);
Copy after login

It is relatively simple to use these classes, just use new:

var people = new People("Alice", "Dickens");
var employee = new Employee("Bob", "Ray", "Alibaba");
var manager = new Manager("Calvin", "Klein", "Alibaba", "Senior Manager");
console.log( people.summary() ); //Alice Dickens
console.log( employee.summary() ); //Bob Ray, Alibaba
console.log( manager.summary() ); //Calvin Klein, Alibaba, Senior Manager
Copy after login

This article is good, so give it a like!

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 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
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 implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles