Home Web Front-end JS Tutorial In-depth understanding of how JavaScript implements inheritance_javascript skills

In-depth understanding of how JavaScript implements inheritance_javascript skills

May 16, 2016 pm 05:09 PM
javascript inherit

Recently, I read online about someone’s experience during an interview with Taobao, and found that there were many things that I was not clear about, so I wrote an article to deepen my understanding of some issues.

A question mentioned in the article is: How does JavaScript implement inheritance?

Below I will explain some methods and examples found on the Internet to deepen my impression.

We know that function in JavaScript is versatile. In addition to being used for function definition, it can also be used for class definition.

JavaScript’s inheritance is a bit strange. Unlike C and some object-oriented languages, it does not have public, private and other access control modifications, and there is no implement or other specific symbols to indicate inheritance.

For inheritance of JavaScript classes, please refer to the following example.

Copy code The code is as follows:


In the above example, a person class is first declared, which contains some attributes and methods, and then a programmer class is declared, which has a base attribute. This attribute is not required, but for the sake of specifications and future You need to write it when looking for the class that the object inherits, and then copy the person class to the programmer's prototype object (prototype); thus realizing class inheritance.

Simulate some principles of classes and inheritance in JavaScript

In object-oriented languages, we use classes to create a custom object. However, everything in JavaScript is an object, so how to create a custom object?

This requires the introduction of another concept - prototype. We can simply regard prototype as a template. The newly created custom objects are all copies of this template (prototype) (actually not copies but It’s a link, but this link is invisible and feels like a copy).

Let’s take a look at an example of creating a custom object through prototype:

Copy the code The code is as follows:

//Constructor
function Person(name, sex) {
this.name = name;
this.sex = sex;
}
// Define Person Prototype, the properties in the prototype can be referenced by custom objects
Person.prototype = {
     getName: function() {
                                                                                                                                           {
                                                                                                                                                                                                                                                                                                  ;
Here we call the function Person a constructor, which is a function that creates a custom object. It can be seen that JavaScript simulates the functions of classes through constructors and prototypes.

The following is an example to illustrate the specific work done by javascript when creating a custom object:

Copy code


The code is as follows:

When the code var zhang = new Person("ZhangSan", "man") is executed, the following things are actually done internally:

Create a blank object (new Object()).
Copy the attributes (key-value pairs) in Person.prototype to this empty object (as we mentioned earlier, the internal implementation is not a copy but a hidden link).
Pass this object into the constructor through the this keyword and execute the constructor.
Assign this object to variable zhang.
All work done.
In order to prove that the prototype template is not copied into the instantiated object, but is a way of linking, please see the following code:

Copy code The code is as follows:

function Person(name, sex) {
this.name = name;
this.sex = sex;
}
Person.prototype.age = 20;
var zhang = new Person("ZhangSan", "man");
console.log(zhang.age); // 20
// Overwrite prototype The age attribute in
zhang.age = 19;
console.log(zhang.age); // 19
delete zhang.age;
// After deleting the instance attribute age, this attribute The value is obtained from prototype
console.log(zhang.age); // 20

In the above example, if it is only obtained by copying, after deleting the age attribute, the object will not exist. However, the age attribute in the example can still be output or overwritten. The previous value indicates that we have only deleted the attribute with the same name in the subclass, and the age attribute in the parent class still exists in the object through an invisible link.

How to implement simple inheritance in JavaScript?

The following example will create an employee class Employee, which inherits all the properties in the prototype prototype from Person.

Copy code The code is as follows:

function Employee(name, sex, employeeID) {
this.name = name;
this.sex = sex;
this.employeeID = employeeID;
}
// Point the prototype of Employee to an instance of Person
// Because Person Instances of Employee can call methods in the Person prototype, so instances of Employee can also call all properties in the Person prototype.
Employee.prototype = new Person();
Employee.prototype.getEmployeeID = function() {
return this.employeeID;
};
var zhang = new Employee("ZhangSan" , "man", "1234");
console.log(zhang.getName()); // "ZhangSan

Okay, the above are some specific processes for implementing inheritance in JavaScript , and methods to implement inheritance .

Of course to summarize, the inheritance mechanism in JavaScript is only based on simulation. Compared with some object-oriented languages, it is rough and has some flaws. However, in general, this still does not slow down front-end development. author’s enthusiasm in this regard.

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
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.

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.

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

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 get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

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.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' 'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' Feb 25, 2024 pm 09:04 PM

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

See all articles