JavaScript OOP Programming-three forms of implementing inheritance [1]
(1) The way of simulating the class, we all know that JS is a prototype inheritance mechanism, there is no class and instance separation of this way
Let's say we have two of classes.
function Animal () {
THIS.name = "Animal";
This.eat = function () {
Consle.log ("eating");
}
}
function Cat () {
This.say = function () {
Console.log ("Miao miao!!");
}
}
If we want cat to have the animal name attribute and the Eat method, you only need to
Cat.prototype = new Animal ();
But this is not a good practice, think about, if there is a duck class, do you want to new a animal to inherit, so continue?
The right thing to do is to put the generic content into the prototype, all the heirs, simply point their prototype to a generic prototype to implement the inheritance.
As follows
Animal.prototype = {
Name: "Animal",
Eat:function () {
Console.log ("eating");
}
}
Cat.prototype = Animal.prototype;
ES5 provides us with a generic inheritance function that creates an object from a specified prototype
Object.create unfortunately not all browsers support, manually change
var inherit = Object.create | | function (proto) {
function F () {};
F.prototype = Proto;
return new F
}
The above example can be written as
Cat.prototype = Inherit (Animal.prototype);
——————————
In doing so, there will be cat.prototype = F case, we need to go to the right, we should write a package, specifically to implement the inheritance
var extend = function (child,parent) {
Child.prototype = Inherit (Parent.prototype);
Child.prototype.constructor = child;
}
JavaScript OOP Programming-three forms of implementing inheritance