JavaScript inheritance for object-oriented easy Entry (demo by ES5, ES6)

Source: Internet
Author: User

inheritance is an object-oriented concept, divided into interface inheritance and implementation of inheritance, interface inheritance is a method to inherit an object, the implementation of inheritance is to inherit the properties of an object. Javvascript implements inheritance by implementing interface inheritance,call (), or apply () through a prototype chain.

the implementation of interface inheritance is ES5 is a hassle, and a extends keyword can be implemented in other OOP languages, but in ES5 In order to simulate through the prototype chain, very difficult to understand, very unfriendly to beginners, and there are several ways to inherit the interface. In order to be more friendly to beginners, do not intend to let the reader understand the principle of interface inheritance, but directly to the interface inheritance implementation method encapsulated into a function, we just take this function to use the past can be.

Related concepts: The parent class (superclass) is the successor, the subclass (derived class) is the successor

Interface Inheritance FunctionsExtend ():
1 function Extend (subclass, superclass) {2 function O () {3          This. constructor =Subclass;4     }5O.prototype =Superclass.prototype;6Subclass.prototype =Newo ();7     returnSubclass.prototype;8 }9 /*Ten subclass is a subclass, superclass is the parent class, the Extend function lets subclass inherit superclass's prototype method, and returns the subclass prototype; One This kind of inheritance is also used most, and the extends of ES6 is realized by this way, which can be said to be more authoritative usage; A */
ES5 Inherit Demo:
1 function Animal (shoutvoice,speed) {2      This. _shoutvoice = Shoutvoice;//string3      This. _speed = speed;//string4 }5Animal.prototype.getSpeed =function () {6     return  This. _speed;7 };8Animal.prototype.shout =function () {9Console.log ( This. _shoutvoice);Ten }; OneAnimal.prototype.run =function () { AConsole.log ('Hey, eat my ashes! I have a speed.'+ This. _speed); - }; -  the function Dog () { -Animal.call ( This,'Wang-woo! ','10m/s'); -     //implementation Inheritance: Call the animal constructor, inherit the properties of the animal class, the first parameter must be this; - } + //interface Inheritance: The extends function allows the dog class to inherit the prototype method of the animal class and return the new prototype prototype of dog; - varDogp =extend (dog,animal); + /*you can continue to add methods to the prototype of the dog class*/ ADogp.gnawbone =function () { atConsole.log ('This is the happiest time for this dog.'); - } - /*You can also override the method of the parent class*/ -Dogp.run =function () { -Console.log ('This is the Run method on the dog class, not the animal class.'); -     /*Although it is covered, the animal class's Run method is still available, and the method of the parent class can be accessed in this way . in students interested in the principle can learn about the prototype chain*/ -Animal.prototype.run.call ( This); to } + varDog =NewDog (); -Console.log (Dog.getspeed ());//log: ' 10m/s ' theDog.shout ();//log: ' Wang-woo! ' * Dog.run (); $ /*log:Panax Notoginseng ' This is the Run method on the dog class, not the animal class ' - ' Hey, eat my ashes! My speed is 10m/s ' the */ +Dog.gnawbone ();//log: ' This is the happiest time for this dog ' the /*Other classes inherit the animal class*/ + function Snake () { -Animal.call ( This,'Hiss! Hiss! Hiss! ','5m/s'); $ } $ varSnakep =extend (snake,animal); - /*The Dog class can also continue to be inherited*/ - function Poodledog () { theDog.call ( This); -      This. _breed ='poodle';Wuyi } the varPoodledogp =extend (poodledog,dog); - /*in theory, you can inherit indefinitely, such as a browser DOM object that inherits a lot of objects, forming a long prototype chain Wu Such as the class inheritance order of a div tag object: - Htmldivelement About but our project best not more than 3 times, otherwise it is not very good control;*/
Precautions:

* Inherit the number of times should not be too much, otherwise the subclass accidentally put the parent class property method to cover;
* We can take the inherited object as the member attribute, namely the combination, as far as possible inherits, the multi-use combination;
* The parent class's properties and methods are best not too much, too much easier to cover the quilt class, can be abstracted into an object to manage too many properties and methods.
* Inheritance increases the coupling, so the parent class encapsulation must be better, to minimize the coupling with the sub-class,
* Parent class design to be forward-looking, with a certain degree of expansion, you do not want to modify the parent class in the future, then to modify all subclasses it?

* The parent class tries to define only the method and does not define the property, i.e. the constructor is preferably an empty function;

ES6 Inherit Demo:

ES6 implementation of the inheritance is much easier, because typescript implementation of inheritance and ES6 almost, so this chapter does not post typescript demo

1 class animal{2 Constructor (shoutvoice,speed) {3          This. _shoutvoice = Shoutvoice;//string4          This. _speed = speed;//string5     }6 get Speed () {7         return  This. _speed;8     }9 shout () {TenConsole.log ( This. _shoutvoice); One     } A run () { -Console.log (' Hey, eat my ashes! My speed is ' + ' This. _speed); -     } the } - class Dog extends animal{ - Constructor () { -Super (' Wang Woo! ', ' 10m/s ');//equivalent to Animal.call (this, ' Wang Woo! ', ' 10m/s '); +     } - Gnawbone () { +Console.log (' This is the happiest time for this dog '); A     } at run () { -Console.log (' This is the Run method on the dog class, not the animal class '); -Super.run ();//equivalent to Animal.prototype.run.call (this); -     } - } - class Poodledog extends dog{ in Constructor () { - super (); to          This. _breed = ' poodle '; +     } - get Breed () { the         return  This. _breed; *     } $ }Panax NotoginsengLet Poodledog =NewPoodledog (); -Console.log (Poodledog.breed);//log: ' Poodle ' theConsole.log (Poodledog.speed);//log: ' 10m/s ' +Poodledog.shout ();//log: ' Wang-woo! ' A Poodledog.run (); the /*log: + ' This is the Run method on the dog class, not the animal class ' - ' Hey, eat my ashes! My speed is 10m/s ' $ */ $Poodledog.gnawbone ();//log: ' This is the happiest time for this dog '
something

JS inheritance and other OOP language there are some different places, so ultimately it is necessary to understand the prototype, prototype chain can be used flexibly, I hope you have time to make this part of the knowledge to fill;

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

The author will try to update a chapter every week, the next chapter is about polymorphism;

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 inheritance for object-oriented easy Entry (demo by ES5, ES6)

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.