JavaScript easy to get started Polymorphic (demo by ES5, ES6, TypeScript)

Source: Internet
Author: User
Tags define abstract

Polymorphism (polymorphism) literally means "multiple states", and the same behavior (methods) have different states on different objects.
In OOP, many places have to use polymorphic features, such as the right mouse button, click the shortcut, click on the blank Space, click on the taskbar and other pop-up menus are different.

Method override (Override):

That is, the subclass defines a method with the same name as the parent class, overriding the parent class method to implement different functions.

1     functionAnimal () {}2     varAnimalp =Animal.prototype;3Animalp.eat =function(food) {4Console.log (' This animal is eating ' +Food );5     };6 7     functionSnake () {}8     varSnakep = Extend (snake,animal);//extend function see a section9     /*Snake does not override the Eat method, the inherited parent class Eat () method*/Ten     functionDog () {} One     varDogp =extend (dog,animal); ADogp.eat =function(food) { -         /*overriding the Eat () method*/ -         /*as mentioned in the previous chapter, the parent method can also be called here through Animal.eat.call (This,food);*/ theConsole.log ("This dog is eating" +Food ); -     }; -  -     functionCat () {} +     varCATP =extend (cat,animal); -Catp.eat =function(food) { +Console.log ("This cat is eating" +Food ); A     }; at     varSnake =NewSnake (); -Snake.eat (' mouse ');//log: The animal is eating mice -     varDog =NewDog (); -Dog.eat (' Bones ');//log: This dog is eating bones . -     varCat =NewCat (); -Cat.eat (' fish ');//log: The cat is eating fish
Abstract class:

In the above code, the snake class does not implement its own eat () method, but sometimes we want the subclass to have a method (abstract method), so that we can standardize the behavior of the subclass, it is necessary to use the abstract class,
ES5, ES6 do not have the concept of abstract class, so we can only be implemented by simulation, let us proceed to the above code, if we want to define the animal eat () method as an abstract method:

1Animalp.eat =function(food) {2         /*Define abstract methods (virtual functions), and if subclasses do not override this method, they will throw an error when executing this method*/3         Throw' "' + This. Constructor.name + "' Class No Eat () method";4     };5     functionSnake () {}6     varSnakep =extend (snake,animal);7     varSnake =NewSnake ();8Snake.eat (' mouse ');//Throw: "Snake" class does not have eat () method

Method Overloading (Overload):

We must have written such a function, depending on the parameters passed in (type, number of parameters), the method will run the same result:

1 varRun =function(speed) {2         if(typeofSpeed = = ' Number '){3Console.log (' Run speed + ' + ' + '/s '));4}Else if(typeofSpeed = = ' String '){5Console.log (' Run speed has ' +Speed );6         }7     }8Run (15);//log: The speed of running is 15m/s9Run (' 20km/h ');//log: The speed of running is 20km/h

But the above is obviously difficult to maintain code, you can use the Run method as an interface, depending on the type of parameters to execute different methods, used in the same class to the following:

1     functionDog () {}2     varDogp =Dog.prototype;3Dogp.run =function(speed) {4         if(typeofSpeed = = ' Number '){5              This. _runnumber (speed);6}Else if(typeofSpeed = = ' String '){7              This. _runstring (speed);8}Else{9             Throw' Parameters do not match ';Ten         } One     } ADogp._runstring =function(speed) { -Console.log (' This dog runs at a speed of ' + ')Speed ); -     } theDogp._runnumber =function(speed) { -Console.log (' This dog runs at a speed of ' + ' + ' + ' m ')); -     } -     varDog =NewDog (); +Dog.run (15);//log: This dog runs at a 15m/s speed. -Dog.run (' 20km/h ');//log: This dog runs at a 20km/h speed. +Dog.run ([]);//Throw: Parameter mismatch

This is the simulation of method overloading, but in fact, ES5, ES6, and typescipt do not support syntax method overloading, and Typescipt only supports function overloading.
This is another way to achieve polymorphism.

Demo by ES6:
1 class animal{2 Eat (food) {3             Throw' "' + This. Constructor.name + "' Class No Eat () method";4         }5     }6 class Snake extends animal{}7 class Dog extends animal{8 Eat (food) {9Console.log ("This dog is eating" +Food );Ten         } One     } A class Cat extends animal{ - Eat (food) { -Console.log ("This cat is eating" +Food ); the         } -     } -Let snake =NewSnake (); -Snake.eat (' mouse ');//Throw: "Snake" class does not have eat () method +Let dog =NewDog (); -Dog.eat (' Bones ');//log: This dog is eating bones . +Let cat =NewCat (); ACat.eat (' fish ');//log: The cat is eating fish

Demo by TypeScript:
1Abstract class animal{//Defining abstract Classes Animal2 constructor () {}3 abstract Eat (food:string) {}4     /*defines the abstract method eat (), and qualifies the passed parameter type to be string,5 can also define the return value, interface, etc., if the subclass does not conform to the specification, compile the time will be error. 6     */7 }8Class Snake extends animal{}//error, unable to compile because no eat () abstract method is defined9 class Dog extends animal{Ten Eat (food:string) { OneConsole.log ("This dog is eating" +Food ); A     } - } - class Cat extends animal{ the Eat (food:string) { -Console.log ("This cat is eating" +Food ); -     } - } +Let dog =NewDog (); -Dog.eat (' Bones ');//log: This dog is eating bones . +Let cat =NewCat (); ACat.eat (' fish ');//log: The cat is eating fish

something

If you like the author's article, remember the collection, your praise is the greatest encouragement to the author;

The main object-oriented knowledge point here is finished, these things are only the foundation, I said certainly not perfect, just for everyone to get started quickly, suggest that you have time or systematic reading study JS OOP;

This series also has the last chapter, will put the previous several knowledge points through a case of integration together, so that we can better digestion and absorption, probably brewing two weeks of time;

You have any questions can leave a message or a private author, the author as far as possible to reply to the first time;

If the old drivers think there can be inappropriate, or can express the better, welcome to point out, I will revise and improve as soon as possible.

JavaScript easy to get started Polymorphic (demo by ES5, ES6, TypeScript)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.