


How javascript uses prototype chain to implement inheritance method summary
Javascript itself is not an object-oriented language, but an object-based language. For people who are used to other OO languages, they are a little uncomfortable at first because there is no concept of "class" here, or " There is no distinction between "class" and "instance", let alone "parent class" and "subclass". So, how are these objects in JavaScript so connected?
Fortunately, JavaScript has provided the implementation of "inheritance" from the beginning of its design. Before understanding "inheritance", let's first understand the concept of the prototype chain.
Prototype chain
The specific code is as follows:
function SuperClass(){ this.name = "women" } SuperClass.prototype.sayWhat = function(){ return this.name + ":i`m a girl!"; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); SubClass.prototype.subSayWhat = function(){ return this.subname + ":i`m a beautiful girl"; } var sub = new SubClass(); console.log(sub.sayWhat());//women:i`m a girl!
Use prototype chain to implement inheritance
It can be seen from the above code that SubClass inherits the properties and methods of SuperClass. This inheritance is realized by assigning the instance of SuperClass to the prototype object of SubClass, so that the prototype object of SubClass is replaced by SuperClass's prototype object. An instance is overwritten, has all its properties and methods, and also has a pointer to the SuperClass prototype object.
There are some things we need to pay attention to when using the prototype chain to implement inheritance:
Pay attention to the changes in the constructor after inheritance. The constructor of sub here points to SuperClass, because the prototype of SubClass points to the prototype of SuperClass. When understanding the prototype chain, don't ignore the default Object object at the end. This is why we can use built-in methods such as toString in all objects.
When implementing inheritance through the prototype chain, you cannot use literals to define prototype methods, because this will overwrite the prototype object:
function SuperClass(){ this.name = "women" } SuperClass.prototype.sayWhat = function(){ return this.name + ":i`m a girl!"; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); SubClass.prototype = {//此处原型对象被覆盖,因为无法继承SuperClass属性和方法 subSayWhat:function(){ return this.subname + ":i`m a beautiful girl"; } } var sub = new SubClass(); console.log(sub.sayWhat());//TypeError: undefined is not a function
Instance sharing problem. When explaining prototypes and constructors earlier, we have introduced that prototypes containing reference type attributes will be shared by all instances. Similarly, the prototypes we inherit will also share the reference type attributes in the "parent class" prototype. When After we modify the reference type attribute of the "parent class" through prototypal inheritance, all other instances inherited from the prototype will be affected. This is not only a waste of resources, but also a phenomenon we do not want to see:
function SuperClass(){ this.name = "women"; this.bra = ["a","b"]; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); var sub1 = new SubClass(); sub1.name = "man"; sub1.bra.push("c"); console.log(sub1.name);//man console.log(sub1.bra);//["a","b","c"] var sub2 = new SubClass(); console.log(sub1.name);//woman console.log(sub2.bra);//["a","b","c"]
Note: When an element is added to the array here, all instances inherited from SuperClass will be affected, but if the name attribute is modified, it will not affect other instances. This is because Arrays are reference types, and name is a basic type.
How to solve the problem of instance sharing? Let’s look down...
Classic inheritance (constructor stealing)
As we have introduced that prototypes are rarely used alone to define objects, in actual development we The prototype chain is rarely used alone. In order to solve the problem of sharing reference types, JavaScript developers have introduced the classic inheritance pattern (also called borrowed constructor inheritance). Its implementation is very simple: calling the super in the subtype constructor. Type constructor. We need to use the call() or apply() function provided by javascript. Let’s take a look at the example:
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } function SubClass() { this.subname = "your sister"; //将SuperClass的作用域赋予当前构造函数,实现继承 SuperClass.call(this); } var sub1 = new SubClass(); sub1.bra.push("c"); console.log(sub1.bra);//["a","b","c"] var sub2 = new SubClass(); console.log(sub2.bra);//["a","b"]
SuperClass.call(this); This sentence means: The initialization work of the SuperClass constructor is called in the SubClass instance (context) environment, so that each instance will have its own copy of the bra attribute, without affecting each other.
However, this implementation is still not perfect. Since the constructor is introduced, we are also faced with the problem of the constructor mentioned in the previous article: If there is a method definition in the constructor, then for Each instance has a separate Function reference. Our purpose is to share this method, and the methods we define in the supertype prototype cannot be called in subtype instances:
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function(){ console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); } var sub1 = new SubClass(); console.log(sub1.sayWhat());//TypeError: undefined is not a function
Combined inheritance
Combined inheritance is a way to combine the advantages of the prototype chain and the constructor to express their respective strengths and combine them to achieve inheritance. , simply put, it uses the prototype chain to inherit properties and methods, and uses the borrowed constructor to realize the inheritance of instance properties. This not only solves the problem of instance property sharing, but also allows super-type properties and methods to be inherited:
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function(){ console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); //第二次调用SuperClass } SubClass.prototype = new SuperClass(); //第一次调用SuperClass var sub1 = new SubClass(); console.log(sub1.sayWhat());//hello
The combined inheritance method is also the most commonly used method for us to implement inheritance in actual development. This can already meet your actual development needs, but people’s pursuit of perfection is endless. , then, someone will definitely be "nitpicky" about this pattern: your pattern calls the supertype constructor twice! Twice. . . Do you think it is a performance loss if it is enlarged a hundred times?
The most powerful rebuttal is to come up with a solution. Fortunately, the developers have found the best solution to this problem:
Parasitic combined inheritance
Before introducing this inheritance method, let us first understand the concept of parasitic constructor. The parasitic constructor is similar to the factory pattern mentioned earlier. Its idea is to define a public function, which is specially used to handle the creation of objects and the completion of creation. After returning this object, this function is very similar to a constructor, but the constructor has no return value:
function Gf(name,bra){ var obj = new Object(); obj.name = name; obj.bra = bra; obj.sayWhat = function(){ console.log(this.name); } return obj; } var gf1 = new Gf("bingbing","c++"); console.log(gf1.sayWhat());//bingbing
寄生式继承的实现和寄生式构造函数类似,创建一个不依赖于具体类型的“工厂”函数,专门来处理对象的继承过程,然后返回继承后的对象实例,幸运的是这个不需要我们自己实现,道哥(道格拉斯)早已为我们提供了一种实现方式:
function object(obj) { function F() {} F.prototype = obj; return new F(); } var superClass = { name:"bingbing", bra:"c++" } var subClass = object(superClass); console.log(subClass.name);//bingbing
在公共函数中提供了一个简单的构造函数,然后将传进来对象的实例赋予构造函数的原型对象,最后返回该构造函数的实例,很简单,但疗效很好,不是吗?这个方式被后人称为“原型式继承”,而寄生式继承正是在原型式基础上,通过增强对象的自定义属性实现的:
function buildObj(obj){ var o = object(obj); o.sayWhat = function(){ console.log("hello"); } return o; } var superClass = { name:"bingbing", bra:"c++" } var gf = buildObj(superClass); gf.sayWhat();//hello
寄生式继承方式同样面临着原型中函数复用的问题,于是,人们又开始拼起了积木,诞生了——寄生组合式继承,目的是解决在指定子类型原型时调用父类型构造函数的问题,同时,达到函数的最大化复用。基于以上基础实现方式如下:
//参数为两个构造函数 function inheritObj(sub,sup){ //实现实例继承,获取超类型的一个副本 var proto = object(sup.prototype); //重新指定proto实例的constructor属性 proto.constructor = sub; //将创建的对象赋值给子类型的原型 sub.prototype = proto; } function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function() { console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); } inheritObj(SubClass,SuperClass); var sub1 = new SubClass(); console.log(sub1.sayWhat()); //hello
这个实现方式避免了超类型的两次调用,而且也省掉了SubClass.prototype上不必要的属性,同时还保持了原型链。
The above is the detailed content of How javascript uses prototype chain to implement inheritance method summary. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

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

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

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.
