search
HomeWeb Front-endJS TutorialDetailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills

ECMAScript only supports implementation inheritance, and its implementation inheritance mainly relies on the prototype chain.

Prototype Chain

The basic idea of ​​prototype chain is to use prototypes to let one reference type inherit the properties and methods of another reference type. Each constructor has a prototype object, the prototype object contains a pointer to the constructor, and the instance contains a pointer to the prototype object. If: we make the prototype object A equal to another instance of type B, then the prototype object A will have a pointer pointing to the prototype object of B, and the corresponding prototype object of B stores a pointer to its constructor. If the prototype object of B is an instance of another type, then the above relationship still holds, and so on, layer by layer, a chain of instances and prototypes is formed.

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills

The relationship diagram between instances and constructors and prototypes is as follows:

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills

person.constructor now points to the Parent. This is because Child.prototype points to the Parent's prototype, and the constructor of the Parent prototype object points to the Parent.

When accessing an instance property in read mode, the property will first be searched for in the instance. If the property is not found, the search for the prototype of the instance will continue. In integration via a prototype chain, the search continues up the chain until the end of the chain is reached.

For example, when calling the person.getParentValue() method, 1) search for instances; 2) search for Child.prototype; 3) search for Parent.prototype; stop when the getParentValue() method is found.

1. Default prototype

The prototype chain shown in the previous example is missing a link. All reference types inherit Object by default, and this inheritance is also implemented through the prototype chain. Therefore, the default prototype contains an internal pointer pointing to Object.prototype. This is the fundamental reason why all custom types inherit default methods such as toString() and ValueOf(). In other words Object.prototype is the end of the prototype chain.

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills

2. Determine the relationship between prototype and instance

The relationship between the prototype and the instance can be determined in two ways. The first is to use the instanceOf operator, and the second is to use the isPrototypeOf() method.
The constructors that appear in the instanceOf prototype chain will all return true

console.log(person instanceOf Child);//true 

console.log(person instanceOf Parent);//true 
console.log(person instanceOf Object);//true 
isPrototype(),只要是原型链中出现过的原型,都可以说是该原型链所派生出来的实例的原型,因此也返回true. 
console.log(Object.prototype.isPrototypeOf(instance));//true 
console.log(Parent.prototype.isPrototypeOf(instance));//true 
console.log(Child.prototype.isPrototypeOf(instance));//true 

3、謹慎定義方法

子類型有時候需要覆寫超類型中的某個方法,或是需要加入超類型中不存在的莫個方法,注意:給原型添加方法的程式碼一定要放在替換原型的語句之後。

當透過Child的實例呼叫getParentValue()時,呼叫的是這個重新定義過的方法,但是透過Parent的實例呼叫getParentValue()時,呼叫的還是原來的方法。

格外需要注意的是:必須要在Parent的實例替換原型之後,再定義這兩個方法。

還有一點要特別注意的是:透過原型鏈實現繼承時,不能使用物件字面量來建立原型方法,因為這樣做會重寫原型鏈。

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills 

以上程式碼剛把Parent的實例賦值給Child的原型對象,緊接著又將原型替換成一個字面量,替換成字面量之後,Child原型實際上包含的是一個Object的實例,而不再是Parent的實例,因此我們設想中的原型鏈被切斷.Parent和Child之間沒有任何關聯。

4、原型鏈的問題

原型鏈很強大,可以利用它來實現繼承,但是也有一些問題,主要的問題還是包含引用類型值的原型屬性會被所有實例共享。因此我們在建構函式中定義實例屬性。但是在透過原型來實現繼承時,原型物件其實變成了另一個類型的實例。於是原先定義在建構函式中的實例屬性變成了原型屬性了。

舉例說明如下:

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills 

在Parent建構函式中定義了一個friends屬性,該屬性值是一個陣列(引用型別值)。這樣,Parent的每個實例都會各自包含自己的friends屬性。當Child透過原型鏈繼承了Parent之後,Child.prototype也用了friends屬性──這就好像friends屬性是定義在Child.prototype一樣。這樣Child的所有實例都會共享這個friends屬性,因此我們對kid1.friends所做的修改,在kid2.friends中也會體現出來,顯然,這不是我們想要的。

原型鏈的另一個問題是:在建立子類型的實例時,不能在不影響所有物件實例的情況下,給超類型的建構函式傳遞參數。因此,我們通常很少會單獨使用原型鏈。

借用建構子

為了解決原型中包含引用類型值所帶來的一些問題,引入了借用構造函數的技術。這種技術的基礎思想是:在子類型建構函數的內部呼叫超類型建構函數。

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills 

Parent.call(this)在新建立的Child實例的環境下呼叫了Parent建構子。在新建立的Child實例環境下呼叫Parent建構函式。這樣,就在新的Child物件上,此處的kid1和kid2物件上執行Parent()函數中定義的物件初始化程式碼。這樣,每個Child實例就都會具有自己的friends屬性的副本了。

借用建構函式的方式可以在子型別的建構子中向超型別建構函式傳遞參數。

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills 

為了確保子類型的熟悉不會被父類別的建構子重寫,可以在呼叫父類別建構子之後,再加入子類型的屬性。
建構子的問題:

建構函式模式的問題,在於方法都在建構函式中定義,函式復用無從談起,因此,借用建構函式的模式也很少單獨使用。

組合繼承

組合繼承指的是將原型鍊和借用構造函數的技術組合在一塊,從而發揮二者之長。即:使用原型鏈實作原型屬性和方法的繼承,而藉由借用建構函式來實現實例屬性的繼承。

Detailed description of several ways to implement inheritance in JavaScript (recommended)_javascript skills 

The Person constructor defines two attributes: name and friends. The prototype of Person defines a method sayName(). When the Child constructor calls the Parent constructor, it passes in the name parameter, and then defines its own attribute age. Then assign the Person instance to the Child prototype, and then define the method sayAge() on the prototype. In this way, two different Child instances have their own attributes, including reference type attributes, and can use the same method.
Combining inheritance avoids the shortcomings of prototype chains and constructors, combines their advantages, and becomes the most commonly used inheritance pattern in JavaScript. Moreover, instanceOf and isPropertyOf() can also recognize objects created based on combined inheritance.

Finally, there are still several modes that have not been written about JS objects and inheritance. In other words, I have not studied them in depth myself. However, I think that I can apply the combination mode with ease first. Moreover, you should know why you choose the combination mode and why.

Regarding several ways to implement inheritance in JavaScript (recommended), the editor will introduce it to you here. I hope it will be helpful to you!

Statement
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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function