Home  >  Article  >  Web Front-end  >  An easy introduction to polymorphism

An easy introduction to polymorphism

零下一度
零下一度Original
2017-07-03 14:18:091049browse

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, if you click the right mouse button, click a shortcut, click a blank space on the desktop, click the taskbar, etc., the pop-up menus will be 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:这只猫正在吃鱼

Afterword

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 That’s it for now. These things are just the basics. What I’ve said is certainly not perfect. It’s just for everyone to get started quickly. I suggest that if you have time, you should systematically read books and learn about js OOP;

There are other chapters in this series The last chapter will integrate the knowledge points mentioned in the previous chapters through a case so that everyone can better digest and absorb it. It will take about two weeks to brew;

If you have any questions, you can leave a message or Private message the author, and the author will try his best to reply to everyone as soon as possible;

If veteran drivers feel that there is something inappropriate or something that can be expressed better, you are welcome to point it out and I will correct and improve it as soon as possible.

The above is the detailed content of An easy introduction to polymorphism. 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