1 functionExtend (child,parent) {2 varf=function(){}3F.prototype=Parent.prototype;4Child.prototype=NewF ();5Child.prototype=Child ;6Child.uber=Parent.prototype;//uber a prototype that points to the parent object. Facilitates the child object to invoke the overridden method in the parent object prototype. 7 }8 functionShape () {}9Shape.prototype.name= "Shape";TenShape.prototype.color= "Blue"; One A functionCircle (RADIUS) { - This. radius=radius; - } the -Circle.prototype.name= "Circle"; -circle.prototype.gets=function(){ - return This. radius* This. radius*3.14; + } - extend (circle,shape); + A varCir=NewCircle (2); atalert (cir.name);//"Circle" -alert (Cir.color);//"Blue" -alert (cir.uber.name);//"Shape" -Alert (Cir.gets ())//"12.56"
The first parameter of the Extend function is the sub-constructor, and the second argument is the parent constructor;
Why the prototype object of a sub-constructor does not directly point to the parent constructor's prototype object, because if Child.prototype=parent.prototype, then the parent-Child prototype object is bound together, that is, the parent-child's prototype object is equal to the reference, which is equivalent to pointing to the same address, The prototype of the child object is changed, and the prototype of the parent object is changed, and if the prototype of the parent object and the child object are traversed, two are found to be identical.
1 varCir=NewCircle (2);2 varshape1=NewShape ();3Cir.prototype.name= "This is Circle";4 5 6 for(varIinchshape1) {7 if(!shape1.hasownproperty (i)) {//traversing non-instance properties8Console.log (i+ ":" +shape1[i]);9 }Ten } One A //name:circle - //Color:blue - //gets:function () { the return This. radius* This. radius*3.14; - } - - + for(varIinchCir) { - if(!Cir.hasownproperty (i)) { +Console.log (i+ ":" +cir[i]); A } at } - - //name:circle - //Color:blue - //gets:function () { - return This. radius* This. radius*3.14; in}.
JS Wrapper inheritance function