Let's talk about javascript prototype inheritance.
In the real sense, Javascript is not an object-oriented language and does not provide traditional inheritance methods, but it provides a prototype inheritance method, use the prototype Attributes provided by Alibaba Cloud to implement inheritance.
Prototype and prototype chain
Before prototype inheritance, we should first talk about prototype and prototype chain. After all, this is the basis for prototype inheritance.
In Javascript, each function has a prototype attribute pointing to its own prototype, and the object created by this function also has a _ proto _ attribute pointing to this prototype, the prototype of the function is an Object, so this Object will also have a _ proto _ pointing to its own prototype, so that the prototype of the Object can be further penetrated layer by layer, forming a prototype chain. The following figure illustrates the relationship between prototype and prototype chain in Javascript.
Each Function is an object created by a Function. Therefore, each Function also has a prototype pointing to a Function. It should be noted that the _ proto _ attribute of each object is actually formed in the prototype chain, rather than the prototype attribute of the function, which is very important.
Prototype inheritance
Basic Mode
The Code is as follows:
Var Parent = function (){
This. name = 'parent ';
};
Parent. prototype. getName = function (){
Return this. name;
};
Parent. prototype. obj = {a: 1 };
Var Child = function (){
This. name = 'child ';
};
Child. prototype = new Parent ();
Var parent = new Parent ();
Var child = new Child ();
Console. log (parent. getName (); // parent
Console. log (child. getName (); // child
This is the simplest method to implement prototype inheritance. The object of the parent class is directly assigned to the prototype of the subclass constructor, in this way, the subclass object can access the attributes in the prototype of the parent class and the parent class constructor. The prototype inheritance diagram of this method is as follows: