Home  >  Article  >  Web Front-end  >  A detailed introduction to polymorphism in JavaScript

A detailed introduction to polymorphism in JavaScript

零下一度
零下一度Original
2017-07-17 14:19:571635browse

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