The best way to implement inheritance in JavaScript is recommended
- 2020-03-30 04:16:23
- OfStack
The easiest ways to implement JavaScript inheritance are the call method (or apply method) and the prototype-chain method, but both have drawbacks, and the mix is a good way to implement inheritance. Here are some examples:
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 Animal class, it has a field attribute age and a function attribute sayAge, and the sayAge method is defined in a prototype way. The Dog class inherits from Animal, and its field property has name in addition to age, through animal.call (this,age); The field property age of Dog inherits from Animal can be implemented and initialized. The first argument to the call method is this pointer to the inherited class, and the second argument is the constructor of the Animal class. In fact, inheritance can be implemented just through the call method, but the only requirement is that the function attributes of the parent class be defined in the constructor, which is not appropriate for the function attributes defined in a prototypical way (it is more intuitive to define the function attributes in a prototypical way than in the constructor). To inherit the function properties defined in Animal's prototype way, the following statement is required: "dog.prototype = new Animal();" . The sayName() function in the Dog class is its own function property.
In addition to this classic way of implementing inheritance, there are currently several free libraries available. But think of all kinds of libraries, the head is big, there is time to study when necessary!