The previous article mentions JavaScript-like inheritance, which makes it much easier for other languages (non-JavaScript) programmers to use JavaScript for inheritance, but with the disadvantage of creating a non-essential constructor, In this article, let's talk about prototype inheritance with JavaScript's own characteristics.
Let's take a look at the following code:
varCar ={color:' Red ', Size:' Big ', GetAttr:function() { return This. Color}}varCAR1 =object.create (Car) Car1.color= ' Blue 'Car1.brand= ' BYD 'Console.log (Car1.color)//BlueConsole.log (Car1.brand)//BYDConsole.log (Car.color)//RedConsole.log (Car.brand)//undefinedvarCAR2 =object.create (Car) car2.getattr=function() { return This. Size}console.log (Car2.getattr ())//BigConsole.log (Car.getattr ())//RedConsole.log (Car1.getattr ())//Blue
The above code is the simplest way to prototype inheritance, "subclass" Inherits the "parent class" property, modify the "subclass" of the property also does not affect the "parent class", "Sub-class" is also a peaceful mutual interference, the perfect implementation of inheritance. The benefit of this inheritance is that there is a lower level of constructor than class inheritance
Of course, create this method is ES5, IE6 7 8 is not supported Oh, below is a compatible method, let the low version IE also to achieve create.
if (! object.create) { function(o) { function F () {} = o return New F () }}
The above code means that the first declaration of a constructor, the prototype of the constructor point to the object that needs to inherit, and finally return the instantiated constructor, in fact, this function is also very good interpretation of the principle of prototype inheritance, "The parent class" attribute exists in the "subclass" of the prototype, if "sub-class" If you rewrite the property or method, then directly use the "subclass" of its own properties or methods, and does not affect the "parent class", if the "subclass" does not have a property or method, then because of the prototype chain, we can find the "parent class" property or method, if no more game over.
In fact, the two kinds of inheritance are similar, play is the prototype chain, but the prototype inheritance more in line with the language characteristics of JavaScript, class-type inheritance more inclined to the concept of "class".
JavaScript-Prototype inheritance