javascript继承

 1 //1.原型链的继承
 2     function Box(){
 3         this.age=12;
 4     }
 5     function Desk(){
 6         this.user="mly";
 7     }
 8     Desk.prototype=new Box();
 9     var desk=new Desk();
10     alert(desk.age);//结果为:12
11     //缺点:子类型还无法给父类型传递参数
 1 //2.对象冒充的继承
 2     function Box(age){
 3         this.age=age;
 4     }
 5     function Desk(age){
 6         Box.call(this,age);
 7     }
 8     var desk=new Desk(1234);
 9     alert(desk.age);//1234
10     //缺点:没有原型
 1 //3.原型链+对象冒充
 2     function Box(age){
 3         this.age=age;
 4     }
 5     Box.prototype.startFunction=function(){
 6         return this.age+"Box";
 7     };
 8     function Desk(user,age){
 9         Box.call(this,age);
10         this.user=user;
11     }
12     Desk.prototype=new Box();//继承原型中的方法
13     var desk=new Desk("mly",12);
14     alert(desk.startFunction());
15     alert(desk.user);
16     alert(desk.age);
17     //缺点:如果继承的函数过多,书写繁琐
 1 //4.寄生组合继承
 2     function obj(o) {//将对象的原型放在某个对象的原型里面并返回
 3         function F(){};
 4         F.prototype = o;
 5         return new F();
 6     }
 7     function create(box, desk) {//实现原型的继承
 8         var f = obj(box.prototype);
 9         f.constructor = desk;//调整原型的指针
10         desk.prototype = f;
11     }
12     function Box(user){
13         this.user=user;
14         if(typeof this.startFunction != "function"){
15             Box.prototype.startFunction=function(){
16                 return this.user+"继承";
17             };
18         }
19     }
20     function Desk(user){
21         Box.call(this,user);//实现对象的继承
22     }
23     create(Box,Desk);
24     var desk=new Desk("mly");
25     alert(desk.startFunction());//结果:mly继承

 

 

posted @ 2013-10-12 09:37  小银光  阅读(153)  评论(0)    收藏  举报