A detailed introduction to polymorphism in JavaScript
Hello friends, today we will continue the previous content. We have already talked about inheritance. Today we will talk about the last manifestation of OOP, which is polymorphism. Because of the flexibility of the JavaScript language, we are There is no way to use the interface, so this also brings some confusion to the js program. You don't have to worry too much about this problem, because the later versions of ECMAScript will solve these problems for us. Again, it's too far away. Back to the topic, OOP polymorphism, we can already clearly understand what inheritance looks like, that is, first declare a parent class, and then we can write many subclasses to inherit the attributes and methods of the parent class. We can achieve the same function as the parent class with the least amount of code. This is inheritance. Immediately, a classmate raised a question: I have read the previous inheritance for a long time, and I can understand it, but I don’t know what its use is. Why do we have to write so many inheritance classes? This question immediately hits the mark and is quite critical. Without the existence of polymorphism, the inheritance we mentioned earlier is really useless, because all our inherited classes are identical copies and have no characteristics. For example:
Polymorphism literally means "multiple states". The same behavior (method) has different states on different objects.
Polymorphic features are used in many places in OOP. For example, when you click the right mouse button, click on a shortcut, click on a blank space on the desktop, click on the taskbar, etc., the pop-up menus are different.
Method override:
That is, the subclass defines a method with the same name as the parent class, thereby overriding the parent class method to achieve different functions.
1 function Animal(){} 2 var AnimalP = Animal.prototype; 3 AnimalP.eat = function(food){ 4 console.log('这个动物正在吃' + food); 5 }; 6 7 function Snake(){} 8 var SnakeP = extend(Snake,Animal);//extend函数请看上一节 9 /*snake没有对eat方法重写,继承的父类eat()方法*/10 function Dog(){}11 var DogP = extend(Dog,Animal);12 DogP.eat = function(food){13 /*对eat()方法重写*/14 /*上一章讲过,也可以在这里通过 Animal.eat.call(this,food)调用父方法;*/15 console.log("这只狗正在吃"+food);16 };17 18 function Cat(){}19 var CatP = extend(Cat,Animal);20 CatP.eat = function(food){21 console.log("这只猫正在吃"+food);22 };23 var snake = new Snake();24 snake.eat('老鼠');//log:这个动物正在吃老鼠25 var dog = new Dog();26 dog.eat('骨头');//log:这只狗正在吃骨头27 var cat = new Cat();28 cat.eat('鱼');//log:这只猫正在吃鱼
Abstract class:
In the above code, the Snake class does not implement its own eat() method, but sometimes we want to subclass it There must be a certain method (abstract method), which can standardize the behavior of subclasses. At this time, abstract classes must be used.
Neither ES5 nor ES6 has the concept of abstract classes, so we can only implement it through simulation. , let us continue the above code, if we want to define Animal's eat() method as an abstract method:
1 AnimalP.eat = function(food){2 /*定义抽象方法(虚函数),如果子类没有重写这个方法,在执行这方法的时候就会抛出错误*/3 throw '"' + this.constructor.name + "'类没有eat()方法";4 };5 function Snake(){}6 var SnakeP = extend(Snake,Animal);7 var snake = new Snake();8 snake.eat('老鼠');//throw:"Snake'类没有eat()方法
Method overload (overload):
We must have written such a function. Depending on the parameters passed in (type, number of parameters), the running results of the method are also different:
1 var run = function(speed){2 if(typeof speed == 'number'){3 console.log('跑的速度有' + speed + 'm/s');4 }else if(typeof speed == 'string'){5 console.log('跑的速度有' + speed);6 }7 }8 run(15);//log:跑的速度有15m/s9 run('20KM/h');//log:跑的速度有20KM/h
But It is obvious that the code written above is difficult to maintain. You can use the run method as an interface to execute different methods according to the type of parameters. When used in a class, it will be as follows:
1 function Dog(){} 2 var DogP = Dog.prototype; 3 DogP.run = function(speed){ 4 if(typeof speed == 'number'){ 5 this._runNumber(speed); 6 }else if(typeof speed == 'string'){ 7 this._runString(speed); 8 }else{ 9 throw '参数不匹配';10 }11 }12 DogP._runString = function(speed){13 console.log('这只狗跑的速度有' + speed);14 }15 DogP._runNumber = function(speed){16 console.log('这只狗跑的速度有' + speed + 'm/s');17 }18 var dog = new Dog();19 dog.run(15);//log:这只狗跑的速度有15m/s20 dog.run('20KM/h');//log:这只狗跑的速度有20KM/h21 dog.run([]);//throw:参数不匹配
This is method duplication Simulation of overloading, but in fact, ES5, ES6, and typescipt do not support grammatical method overloading, and typescipt only supports function overloading.
This is another way to implement polymorphism.
Demo by ES6:
1 class Animal{ 2 eat(food){ 3 throw '"' + this.constructor.name + "'类没有eat()方法"; 4 } 5 } 6 class Snake extends Animal{} 7 class Dog extends Animal{ 8 eat(food){ 9 console.log("这只狗正在吃"+food);10 }11 }12 class Cat extends Animal{13 eat(food){14 console.log("这只猫正在吃"+food);15 }16 }17 let snake = new Snake();18 snake.eat('老鼠');//throw:"Snake'类没有eat()方法19 let dog = new Dog();20 dog.eat('骨头');//log:这只狗正在吃骨头21 let cat = new Cat();22 cat.eat('鱼');//log:这只猫正在吃鱼
Demo by TypeScript:
1 abstract class Animal{//定义抽象类Animal 2 constructor(){} 3 abstract eat(food: string){} 4 /*定义抽象方法eat(),并且限定传入的参数类型是string, 5 还可以定义返回值,接口等,如果子类不符合限定的规范,编译的时候就会报错。 6 */ 7 } 8 class Snake extends Animal{}//报错,无法通过编译,因为没有定义eat()抽象方法 9 class Dog extends Animal{10 eat(food: string){11 console.log("这只狗正在吃"+food);12 }13 }14 class Cat extends Animal{15 eat(food: string){16 console.log("这只猫正在吃"+food);17 }18 }19 let dog = new Dog();20 dog.eat('骨头');//log:这只狗正在吃骨头21 let cat = new Cat();22 cat.eat('鱼');//log:这只猫正在吃鱼
After Words
If you like the author’s article, remember to bookmark it. Your likes are the greatest encouragement to the author;
The main knowledge points of object-oriented are finished here. Things are just the basics. What I have said is definitely not perfect. It is just for everyone to get started quickly. It is recommended that if you have time, you should systematically read and learn js OOP;
The above is the detailed content of A detailed introduction to polymorphism in JavaScript. 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











Diffusion can not only imitate better, but also "create". The diffusion model (DiffusionModel) is an image generation model. Compared with the well-known algorithms such as GAN and VAE in the field of AI, the diffusion model takes a different approach. Its main idea is a process of first adding noise to the image and then gradually denoising it. How to denoise and restore the original image is the core part of the algorithm. The final algorithm is able to generate an image from a random noisy image. In recent years, the phenomenal growth of generative AI has enabled many exciting applications in text-to-image generation, video generation, and more. The basic principle behind these generative tools is the concept of diffusion, a special sampling mechanism that overcomes the limitations of previous methods.

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

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

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.

Title: A must-read for technical beginners: Difficulty analysis of C language and Python, requiring specific code examples In today's digital age, programming technology has become an increasingly important ability. Whether you want to work in fields such as software development, data analysis, artificial intelligence, or just learn programming out of interest, choosing a suitable programming language is the first step. Among many programming languages, C language and Python are two widely used programming languages, each with its own characteristics. This article will analyze the difficulty levels of C language and Python

As a widely used programming language, C language is one of the basic languages that must be learned for those who want to engage in computer programming. However, for beginners, learning a new programming language can be difficult, especially due to the lack of relevant learning tools and teaching materials. In this article, I will introduce five programming software to help beginners get started with C language and help you get started quickly. The first programming software was Code::Blocks. Code::Blocks is a free, open source integrated development environment (IDE) for
