We recommend that you use JavaScript to implement inheritance in the best way.
The simplest way to implement JavaScript inheritance is the call method (or the apply method) and the prototype chain method. However, both methods have defects, and their mixture is a good inheritance implementation method. The following is an example:
Copy codeThe Code 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 sayAge. The definition of the sayAge method uses the prototype method. The Dog class must inherit Animal, and its field attributes have name besides age, which can be inherited and initialized by Dog through Animal. call (this, age. The first parameter of the call method is the this pointer of the inherited class, and the second parameter is the parameter of the constructor of the Animal class. In fact, only the call method can be used to implement inheritance, but the only requirement is that the function attribute of the parent class should be defined in the constructor, this is not suitable for defining function properties using the prototype (defining function properties using the prototype is more intuitive than defining function properties within the constructor ). To inherit the function attributes defined by the Animal prototype, the required statement is "Dog. prototype = new Animal ();". The sayName () function in the Dog class is its own function attribute.
In addition to the most classic method of implementation inheritance, there are currently some free libraries available. However, if you think of a variety of libraries, the header will be big. If you have time to study it again!