Web Front-end
JS Tutorial
Detailed explanation of JavaScript prototype and inheritance examples
Detailed explanation of JavaScript prototype and inheritance examples
Prototype chain
Every object in JavaScript has a built-in _proto_ attribute. This attribute is invisible to programming. It is actually a function of the other objects. An object or a reference to null.
#When an object references an attribute, the JavaScript engine will first search it from the object's own attribute table. If found, it will perform corresponding read and write operations. If it is not found in its own attribute table, search in the attribute table of the object referenced by the _proto_ attribute, and so on until this attribute or _proto_ is found. The attribute points to null.
The reference chain of _proto_ is called the prototype chain .
Note that there is a performance optimization problem here: the deeper you search in the prototype chain, the more time it takes.
Prototype chain and constructor
JavaScript is an object-oriented language and can Prototypal inheritance.
The function in JavaScript has an attribute prototype, this prototype attribute is an object, one of its attributes constructorReferences the function itself. That is:
func.prototype.constructor === func; // ==> true
What is the use of this attribute? We know that when a function is called using the new operator, it will return a new object as a constructor. The _proto_ property of this object refers to the prototype property of its constructor.
So this is not difficult to understand:
var obj = new Func(); obj.constructor == Func; // ==> true
There is also this:
obj instanceof Func; // ==> true
It is also by looking up the prototype chain Implemented by the constructor attribute.
The _proto_ attributes of different instances generated by the constructor are references to the same prototype object. So modifying the prototype object will affect all instances.
Several ways of "subclass" inheritance implementation
The reason why subclasses need to be quoted is because the concept of "class" is not rigorous here. JavaScript is an object-oriented language, but unlike Java and other languages, it does not have class definitions before the ES6 standard is released.
But programmers who are familiar with languages such as Java also hope that when using JavaScript, they can generate instances through classes and reuse code through subclasses, similar to using Java. So before ES6, how to use a "class"-like method like the following code?
var parent = new Parent("Sam");var child = new Children("Samson");
parent.say(); // ==> "Hello, Sam!"child.say(); // ==> "Hello, Samson! hoo~~"child instanceof Parent; // ==> trueWe see that here we use the constructor as a class.
Let’s discuss several ways to implement it:
The simplest way
Combined with the concept of prototype chain, we can easily write such code:
function Parent(name){this.name = name;
}
Parent.prototype.say = function(){
console.log("Hello, " + this.name + "!");
}function Children(name){this.name = name;
}
Children.prototype = new Parent();
Children.prototype.say = function(){
console.log("Hello, " + this.name + "! hoo~~");
}The disadvantage of this method is obvious: as a constructor of a subclass, it needs to rely on an object of the parent class. The properties name in this object are completely useless.
First improvement
// ...Children.prototype = Parent.prototype;// ...
So that useless parent class attributes will not be generated.
However, in this case, the prototypes of the subclass and the parent class refer to the same object, and modifying the prototype of the subclass will also affect the prototype of the parent class.
At this time we discovered:
parent.say(); // ==> "Hello,Sam! hoo~~"
This first improvement is worse than no change at all.
The second improvement - temporary constructor/Object.create()
function F(){ // empty }
F.prototype = Parent.prototype;
Children.prototype = new F();// ...parent.say(); // ==> "Hello, Sam!"child.say(); // ==> "Hello, Samson! hoo~~"In this way, modifying the prototype of the subclass is just Modified the properties of a instance of F without changing Parent.prototype, thus solving the above problem.
In the era of ES5, we can also do this directly:
Children.prototype = Object.create(Parent.prototype);
这里的思路是一样的,都是让子类的prototype不直接引用父类prototype。目前的现代浏览器几乎已经添加了对这个方法的支持。(但我们下面会仍以临时构造函数为基础)
但是细细思考,这个方案仍有需要优化的地方。例如:如何让父类的构造函数逻辑直接运用到子类中,而不是再重新写一遍一样的?这个例子中只有一个name属性的初始化,那么假设有很多属性且逻辑一样的话,岂不是没有做到代码重用?
第三次改进——构造函数方法借用
使用apply/call,实现“方法重用”的思想。
function Children(name){
Parent.apply(this, arguments);// do other initial things}“圣杯”模式
现在完整的代码如下:
function Parent(name){this.name = name;
}
Parent.prototype.say = function(){
console.log("Hello, " + this.name + "!");
}function Children(name){
Parent.apply(this, arguments);// do other initial things}function F(){ // empty }
F.prototype = Parent.prototype;
Child.prototype = new F();
Children.prototype.say = function(){
console.log("Hello, " + this.name + "! hoo~~");
}这就是所谓“圣杯”模式,听着很高大上吧?
以上就是ES3的时代,我们用来实现原型继承的一个近似最佳实践。
“圣杯”模式的问题
“圣杯”模式依然存在一个问题:虽然父类和子类实例的继承的prototype对象不是同一个实例,但是这两个prototype对象上面的属性引用了同样的对象。
假设我们有:
Parent.prototype.a = { x: 1};// ...那么即使是“圣杯”模式下,依然会有这样的问题:
parent.x // ==> 1child.x // ==> 1child.x = 2; parent.x // ==>2
问题在于,JavaScript的拷贝不是 深拷贝(deepclone)
要解决这个问题,我们可以利用属性递归遍历,自己实现一个深拷贝的方法。这个方法在这里我就不写了。
ES6
ES6极大的支持了工程化,它的标准让浏览器内部实现类和类的继承:
class Parent {
constructor(name) { //构造函数 this.name = name;
}
say() {
console.log("Hello, " + this.name + "!");
}
}
class Children extends Parent {
constructor(name) { //构造函数super(name); //调用父类构造函数// ... }
say() {
console.log("Hello, " + this.name + "! hoo~~");
}
}从此走上强类型的不归路。。。
上张顿悟图

什么?还不明白?!麻烦出门左拐。推荐阮老师JavaScript万物诞生记。
The above is the detailed content of Detailed explanation of JavaScript prototype and inheritance examples. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1384
52
Recommended: Excellent JS open source face detection and recognition project
Apr 03, 2024 am 11:55 AM
Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side
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.
The relationship between js and vue
Mar 11, 2024 pm 05:21 PM
The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
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?
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.
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
Introduction to the new map of Genshin Impact version 4.4
Jan 31, 2024 pm 06:36 PM
Introducing the new map of Genshin Impact version 4.4. Friends, Genshin Impact 4.4 version also ushered in the Sea Lantern Festival in Liyue. At the same time, a new map area will be launched in version 4.4 called Shen Yu Valley. According to the information provided, Shen Yugu is actually part of Qiaoying Village, but players are more accustomed to calling it Shen Yugu. Now let me introduce the new map to you. Introduction to the new map of Genshin Impact version 4.4. Version 4.4 will open "Chenyu Valley·Shanggu", "Chenyu Valley·Nanling" and "Laixin Mountain" in the north of Liyue. Teleportation anchor points have been opened for travelers in "Chenyu Valley·Shanggu" . ※After completing the prologue of the Demon God Quest·Act 3: The Dragon and the Song of Freedom, the teleportation anchor point will be automatically unlocked. 2. Qiaoyingzhuang When the warm spring breeze once again caressed the mountains and fields of Chenyu, the fragrant
'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


