Home >Web Front-end >JS Tutorial >Recommend the best way to implement inheritance in JavaScript
This chapter introduces the best way to implement JavaScript inheritance using the practical call method combined with the prototype chain method. It is very practical and friends in need can refer to it.
The simplest way to implement JavaScript inheritance is the call method (or apply method) and the prototype chain method, but both methods have flaws, and their mixture is a good way to implement inheritance. The following is an example:
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 a function attribute sayAge. The sayAge method is defined in a prototype way. The Dog class must inherit Animal, and its field attributes include name in addition to age. Through Animal.call(this,age);, Dog can inherit the field attribute age of Animal and initialize it. 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, inheritance can be achieved just 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 using the prototype method (using the prototype method to define Function properties are more intuitive than defining them within a constructor). To inherit the function attributes defined in Animal's prototype mode, 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 of implementing inheritance, there are currently some free libraries available. But thinking about all kinds of libraries is overwhelming. Let’s study it when we have time and need!