///1, borrowing inheritance to clone a sub instance object from the attribute method in the SUP's constructorfunction Super () {this.val = 1; THIS.FUN1 = function () {console.log (' fun1 ')}; } Super.prototype.name = "name"; Super.prototype.fun2 = function () {console.log (' fun2 ')}; function Sub () {super.call (this); } var sub1 = new Sub (); var sub2 = new Sub (); Console.log (sub1.fun1 = = = SUB2.FUN1); Console.log (Sub1.val); Console.log (Sub1.name); Sub1.fun1 ();
///2, prototype inheritance take the instance object of super as the prototype property of the Sub constructorfunction Super () {this.val1 = 1; THIS.FUN1 = function () {Console.log (1)}; } var pro = new Super (); function Sub () {} sub.prototype = Pro; var sub1 = Sub ();
///3, the parasitic sub instantiation object adds its own property method and takes the super instance object as the prototype property of the Sub constructorfunction Super () {this.val1 = 1; THIS.FUN1 = function () {Console.log (1)}; } Super.prototype.val2 = 2; Super.prototype.fun2 = function () {Console.log (2)}; function Sub () {} Sub.prototype = new Super (); var sub1 = new Sub (); SUB1.ATTR1 = 1; SUB1.ATTR2 = 2;
//4, combined inheritance the attribute method in the SUP's constructor is cloned into a sub instance object, and the super instance object is taken as the prototype property of the Sub constructor .function Super () {this.val1 = 1; THIS.FUN1 = function () {Console.log (1)}; } Super.prototype.val2 = 2; Super.prototype.fun2 = function () {Console.log (2)}; function Sub () {super.call (this); } Sub.prototype = new Super (); var sub1 = new Sub (); var sub2 = new Sub (); Console.log (SUB1); Console.log (sub1.fun1 = = = SUB2.FUN1); Console.log (sub1.fun2 = = = sub2.fun2);
///5. The prototype property of the parasitic sub-constructor is the third constructor (its prototype is the SUP prototype, but there is no attribute method in the Sup constructor), and the attribute method in the SUP constructor is cloned into a sub instance object function beget (obj) { //child functions beget: Dragon Beget Dragon, Phoenix beget chicken. var f = function () {}; F.prototype = obj; return new F (); } &NBSP ; function Super () { //Only basic and reference properties are declared here This.val = 1; &nbs P This.arr = [1]; } // declare a function here SUPER.PROTOTYPE.FUN1 = function () { }; Super.prototype.fun2 = function () {}; //super.prototype.fun3... function Sub () { Super.call (this); //core //... &NB Sp } var proto = Beget (Super.prototype); Core Proto.constructor = sub; //core Sub.prototype = pr oto; //core var sub = new Sub (); alert (sub. Val); alert (Sub.arr);
JS in 5 inheritance mode analysis