search
HomeWeb Front-endJS TutorialA detailed introduction to polymorphism in JavaScript
A detailed introduction to polymorphism in JavaScriptJul 17, 2017 pm 02:19 PM
javascriptjsgetting Started

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!

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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.