首页 > Web开发 > 详细

js实现继承

时间:2015-03-15 13:41:53      阅读:329      评论:0      收藏:0      [点我收藏+]

一、原型继承

            function Father(lastname,sex){
                this.lastname=lastname;    //
                this.sex=sex;//性别    
            }
            //父类原型属性
            Father.prototype.xo=‘xxx‘;
            
            //子类
            function Son(firstname){
                this.firstname=firstname;//
            }
                    
            Son.prototype=new Father(‘杨‘); //原型继承,son的原型已经指向了father对象的实例
            
            var son =  new Son(‘清‘);
            alert(son.firstname);//
            alert(son.lastname);//杨  继承的属性
            alert(son.xo);//xxx  继承的原型属性
            alert(son.sex);//undefined//继承时未传值

缺点:继承后还必须给父类传参, new Father(‘杨‘), 不能把参数直接传入子类中

二、借用构造函数继承

            //父类
            function Father(lastname,sex){
                this.lastname=lastname;    //
                this.sex=sex;//性别    
            }
            //父类原型属性
            Father.prototype.xo=‘xxx‘;
            
            //子类
            function Son(lastname,firstname){
                Father.call(this,lastname);//将Father构造函数绑定到Son
                this.firstname=firstname;//
            }
                
            var son =  new Son(‘杨‘,‘清‘);
            alert(son.firstname);//
            alert(son.lastname);//杨  继承的属性
            alert(son.xo);//undefined  未能继承到原型属性
            alert(son.sex);//undefined//不需要继承属性

缺点:未能继承到原型属性

三、 组合继承(原型继承+借用构造函数继承)

            function Father(lastname,sex){
                this.lastname=lastname;    //
                this.sex=sex;//性别    
            }
            //父类原型属性
            Father.prototype.xo=‘xxx‘;
            
            //子类
            function Son(lastname,firstname){
                Father.call(this,lastname);//借用构造函数继承
                this.firstname=firstname;//
            }
            Son.prototype=new Father(); //原型继承,不用传参 只为继承原型属性
            var son =  new Son(‘杨‘,‘清‘);
            alert(son.firstname);//
            alert(son.lastname);//杨  继承的属性
            alert(son.xo);//xxx  继承到原型属性
            alert(son.sex);//undefined//不需要继承属性

 

js实现继承

原文:http://www.cnblogs.com/yangjingqi/p/4339592.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!