How JavaScript implements inheritance in a hybrid way

Source: Internet
Author: User

The simplest way to implement JavaScript inheritance is the call method (or the Apply method) and the prototype chain method, but both of these methods are flawed, and their hybrid is a good way to implement inheritance. The following examples illustrate:

function Animal (age) {
This.age = age;
}

Animal.prototype.sayAge = function () {
Window.alert ("My Age is" +this.age+ "!");
};

function Dog (age,name) {
Animal.call (This,age);
THIS.name = name;
}
Dog.prototype = new Animal ();
Dog.prototype.sayName = function () {
Window.alert ("I am a" +this.name+ "!");
};

var dog = new Dog ("Dog");
Dog.sayname ();
Dog.sayage ();

For the class animal, it has a field property of age and the definition of the function attribute Sayage,sayage method is the prototype mode. The dog class inherits the animal, and its field properties have name in addition to age, through Animal.call (This,age), and you can implement the field attribute of the dog inheritance animal and initialize it. The first parameter of the call method is the this pointer of the inheriting class, and the second argument is the parameter of the constructor of the animal class. In fact, inheritance can be achieved only through the call method, but the only requirement is that the function properties of the parent class are defined in the constructor, which is not appropriate for the function properties used in the stereotype definition (it is more intuitive to define the function properties in a prototype way than in the constructor). To inherit the function properties defined by the Animal prototype, the required statement is "Dog.prototype = new Animal ();". and the Sayname () function in the dog class is its own function property.
In addition to this most classic way to implement inheritance, there are currently some free libraries available for use. But think of all kinds of libraries, the head is big, there is time when necessary to study it!

How JavaScript implements inheritance in a hybrid way

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.