js 继承

    function Person(name) {  
        this.name = name;  
  
         this.getName = function(){  
             return this.name;  
        };  
    }  
       
    function Student(name,score) {  
       this.newPerson = Person;
       this.newPerson(name);
       delete this.newPerson;//赋值之后一定要删掉,避免多重继承时导致的属性,方法覆盖

       //Person.call(this, name);//同上等价


       //Person.apply(this, arguments);//同上等价
        
       this.score=score;  
         
       this.getScore=function(){  
             return score;     
       };  
    }  

以上的代码是通过对象冒充来实现的继承(也可通过call和apply方法替代来达到同样的结果)
这种方法依赖内部构造器,Person添加到prototype下面的方法或属性都将无法继承到
根据上面的写法我们很容易就可以想到他可以继承多个类

再看下面这种方法
    function Person(name) {  
        this.name = name;  
  
        this.getName = function(){  
            return this.name;  
        };  
    }  
       
    function Student() {  
  
    }  
    Student.prototype = new Person();
    
    Student.prototype.score = '';
    
    Student.prototype.getScore = function() {
        return this.score;
    }
这是通过给原型链赋值来达到继承的目的的,很显然这种方法只能继承一个类,多个的话直接会被最新的覆盖掉
虽然他会继承到父类中所有的属性,但他无法通过构造器进行赋值,也就是说只能通过手动从Student.prototype中找到对应的属性
赋值,这并不是我们想要的结果
因此就出现了混合继承(将两者合二为一)
   function Person(name) {  
       this.name = name;
        
       this.getName = function(){  
            return this.name;  
       };  
    }  
       
    function Student(name,score) {  
        Person.call(this, name);

        this.score = score;
    }


    Student.prototype = new Person();

    Student.prototype.getScore = function () {
        return this.score;
    }


   以此来达到上面两种继承的合并

 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值