We know that the attributes in the parent class haveThis, static, and prototype. There are two common inheritance methods:
- Prototype inheritance: All prototype attributes of the parent class can be inherited.
- Object impersonating: You can inherit the this attribute of the parent class, and then inherit the static attribute of the parent class in combination with the for... in loop.
Based on these two methods,Delete unnecessary attributes, AndOverride the parent attributeTo achieve the perfect inheritance effect.
/*** Filename: prefectextend. js * Description: This Program The inheritance of * js will be perfectly realized through three mechanisms: Prototype inheritance, object impersonating, and overwriting. * Date: 2012/3/7 * // *** the parent class animal, and the construction of this, static, and prototype attributes. */Animal = function (tail) {This. tail = tail | "animal's tail"; // This attribute of the parent class this. kinds = "animal"; animal. instancecounter ++; // static attribute of the parent class} animal. instancecounter = 0; animal. prototype = {// The prototype attribute of the parent class: Happy: function () {console. log ("Shake>" + this. tail) ;}, eat: function () {console. log ("animal eating") ;}, run: function () {console. log ("Four animal leg Run") ;}, fight: function () {console. log ("Animal hitting") ;}// if this is not done here, then animal. prototype. constructor = object. For details, see [2] animal. prototype. constructor = animal;/*** 1. object impersonating: inherit this and static attributes * // sub-class personperson = function (name) {person. superclass. call (this); // This property inherits delete this. tail; // Delete this attribute that is not required. name = Name | "hunting empty de Code "; For (var p in animal) {// Static Property inherits person [p] = animal [p] ;}} person. superclass = animal;/*** 2. prototype inheritance */F = function () {}// shell function, used to clear the structure attribute (this and static) F of animal. prototype = animal. prototype; person. prototype = new F (); Delete person. prototype. fight; // Delete the unneeded prototype attribute person. prototype. constructor = person;/*** 3. the prototype method overwrites */person. prototype. eat = function () {console. log (this. name + "familiar");} // create an instance var person = new person (); console. log ("name:" + person. name); console. log (person. kinds); console. log ("number of instances" + person. instancecounter); person. happy (); person. eat (); person. run ();
Program running result:
References:
[1] ext, desert poor autumn, Beijing: Electronic Industry Press, 2012.1 (this program basically imitates this writing)
[2] JavaScript class and inheritance: constructor attributes