//父类 function Aa(){ this. name= "小名"; }; Aa. prototype. showName= function(){ return this. age= 10; }; //子类 function Bb(){ }; Bb. prototype= new Aa(); //实现继承 var b1= new Bb(); alert( b1. name); //小名 //----------------------------------------------------------------------------- //上面的继承有几点问题:1.constractor的指向被改变了 alert( b1. constructor ); // 弹出结果为: function Aa(){ this. name= "小名"; }; //所以 constractor的指向被改变了;修正指向 Bb. prototype = new Aaa(); //这个就叫做类式继承 Bb. prototype. constructor= Bb; //修正指向问题 //----------------------------------------------------------------------------- // 2.子类可以改变父类的属性 //如果上面的代码改成
//父类 function Aa(){ this. name=[ 1, 2, 3]; }; //子类 function Bb(){ }; Bb. prototype= new Aa(); //实现继承 var b1= new Bb(); b1. name. push( 4); var b2= new Bb(); console. log( b2. name); //[1,2,3,4] //----------------------------------------------------------------------------- //此处的b1 b2相互影响了,改变了父类函数Aa,所以是有问题的,上面的代码可改成: //父类 function Aa(){ this. name= "小名"; }; Aa. prototype. showName= function(){ return this. age= 10; }; //子类 function Bb(){ }; var F= new f(); F. prototype= Aa. prototype; //此处只能传递方法,没有办法传递属性 var b1= new Bb(); Bb. prototype= new F(); //把F的实例赋给Bb的原型 console. log( b1. age);
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄