The easiest way to implement JavaScript inheritance is the call method (or apply method) and the prototype chain method, but both methods have shortcomings, and their mixture is a good inheritance implementation method. Here are examples:
The code copy is as follows:
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(15,"dog");
dog.sayName();
dog.sayAge();
For the class Animal, it has a field attribute age and function attribute saysAge. The definition of the sayAge method uses the prototype method. Dog class must inherit Animal, and its field attributes also have name in addition to age. Through Animal.call(this,age); Dog can inherit Animal's field attribute age and initialize it. The first parameter of the call method is this pointer to the inherited class, and the second parameter is the parameter of the constructor of the Animal class. In fact, inheritance can be achieved through the call method, but the only requirement is that the function attributes of the parent class must be defined in the constructor, which is not suitable for the function attributes here to be defined in the prototype (defining function attributes in the prototype is more intuitive than defining in the constructor). To inherit the function attributes defined by Animal's prototype, the required statement is "Dog.prototype = new Animal();". The sayName() function in the Dog class is its own function attribute.
In addition to this most classic way to implement inheritance, there are currently some free libraries available. But when you think of all kinds of libraries, you will be very immense. Let’s study it when you have time and need it!