js中call和apply的继承

这两个方法,已经讲过,是调用函数的,当然也能调用构造函数

function Person(newId,newName){
        this.id = newId;
        this.name = newName;
    }
    function Student(newId,newName,newScore){
        //借用构造方法
        Person.call(this,newId,newName);
        this.score = newScore;
    }
    
    let student = new Student("007","老王",99);
    console.log(student.id,student.name,student.score);

但是这样的继承的方式也有弊端:
1.无法继承父类原型上的属性和方法
2.单独使用这种借用的模式,所有要继承的属性和方法都要在父类型的构造函数里定义,
特别是实例共享的属性和方法也写在构造函数里,那么这样会浪费内存。所以,很少很少单独使用

        //如:
    function Person(newId,newName){
        this.id = newId;
        this.name = newName;
    }
    Person.prototype.eat = function(){
        console.log("Person eat");
    }
    function Student(newId,newName,newScore){
        //借用构造方法
        Person.call(this,newId,newName);
        this.score = newScore;
    }
    
    let student = new Student("007","老王",99);
    console.log(student.id,student.name,student.score);
    student.eat();//报错

必须改成以下形式

 function Person(newId,newName){
        this.id = newId;
        this.name = newName;
        this.eat = function(){
            console.log("Person eat");
        }
    }

    function Student(newId,newName,newScore){
        //借用构造方法
        Person.call(this,newId,newName);
        this.score = newScore;
    }
    
    let student = new Student("007","老王",99);
    console.log(student.id,student.name,student.score);
    student.eat();

组合继承:
结合前两种方式:原型链式继承和Call()/Apply()方式继承,我们就能解决前面提出的那些问题。
利用原型链继承共有的属性和方法,利用Call/Apply来初始化自己的但是和父类型同名的属性或方法。

  function Person(newId,newName){
        this.id = newId;
        this.name = newName;
    }
    Person.prototype.eat = function(){
        console.log("Person eat");
    }
    function Student(newId,newName,newScore){
        Person.call(this,newId,newName);
        this.score = newScore;
    }
    
    Student.prototype = new Person();
    let student = new Student("007","老王",99);
    console.log(student.id,student.name,student.score);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值