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