js继承

继承 :子类继承父类
声明一个父类:属性和行为
声明一个子类对象
面向对象 有三大特征: 封装 继承 多态
1、原型链继承(核心: 将父类的实例作为子类的原型)
优点:非常纯粹的继承关系,实例是子类的实例,也是父类的实例
父类新增原型方法/原型属性,子类都能访问到,简单,易于实现
缺点:要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中
无法实现多继承
创建子类实例时,无法向父类构造函数传参

 function animal() {
        this.name = null;
        this.sex = null;
        this.sleep = function () {
            return this.name + "睡觉";
        }
    }
    function cat() {
        this.type = "猫科";
    }
    cat.prototype = new animal();
    cat.prototype.color = "white";
    var Cat = new cat();
    console.log(Cat)
    console.log(Cat instanceof cat);
    console.log(Cat instanceof animal);

在这里插入图片描述
2、构造继承
call apply 对象指针的替换
区别: 传递的参数的方式不一样
call 有多个参数
apply 有两个参数
优点:创建子类实例时,可以向父类传递参数
可以实现多继承(call多个父类对象)
缺点:实例并不是父类的实例,只是子类的实例
只能继承父类的实例属性和方法,不能继承原型属性/方法
无法实现函数复用,每个子类都有父类实例函数的副本,影响性能


function animal1() {
    this.color = arguments[0];
    this.sleep = function () {
        return this.name + "正在睡觉";
    }
}
function animal2() {
    this.name = arguments[0];
    this.sex = arguments[1];
    this.eat = function () {
        return this.name + "正在吃饭";
    }
}
function dog(name, sex, color) {
    this.type = "犬科";
    animal1.call(this, color);
    animal2.apply(this, [name, sex]);
}
var Dog = new dog("张三", "男", "黑色");
console.log(Dog);
console.log(Dog.sleep());
console.log(Dog.eat());
console.log(Dog instanceof dog);
console.log(Dog instanceof animal1);
console.log(Dog instanceof animal2);

在这里插入图片描述
3、实例继承
new对象返回对象
优点:不限制调用方式,不管是new 子类()还是子类(),返回的对象具有相同的效果
缺点:实例是父类的实例,不是子类的实例
不支持多继承


function animal3(){
    this.name=null;
    this.run=function(){
        return this.name+"正在跑步";
    }
}
function f1(){
    var f1=new animal3();
    return f1;
}
var ff=new f1( );
console.log(ff);
console.log(ff.run());

在这里插入图片描述
4、组合继承 去弥补原型链继承和构造继承的缺点

function Mutou() {
        this.name = arguments[0];
        this.make = function () {
            return "制作" + this.name;
        }
    }

    function Bandeng(name) {
        Mutou.call(this, name);
    }
    Bandeng.prototype = new Mutou();
    var ban = new Bandeng("板凳");
    console.log(ban);
    console.log(ban.make());
    console.log(ban instanceof Bandeng);
    console.log(ban instanceof Mutou);

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值