JS中的继承

原型链继承:

    /**1.原型链继承:
     *     子类型的原型为父类型的实例对象
     */
    function Supper() {  //父类型
        this.propName = 'sup';
    }
    Supper.prototype.display = function () {  //父类型的原型中添加display方法
        alert(this.propName);
    }
    function Subber() {  //子类型
        this.propName = 'sub';
    }
    Subber.prototype = new Supper();  //子类型的原型是父类型的实例对象
    Subber.prototype.constructor = Subber;  //修正子类型的原型的constructor属性
    var sub = new Subber();
    sub.display();  //sub  子类型继承了父类型的display方法

借用构造函数继承:

    /**2.借用构造函数继承:
     *     定义父类型构造函数
     *     定义子类型构造函数
     *     在子类型构造函数中调用父类型构造函数
     */
    function Supper(name, age) {
        this.name = name;
        this.age = age;
    }
    function Subber(name, age, num) {
        Supper.call(this, name, age);
        this.num = num;
    }
    var sub = new Subber('doggy', 18, 68);  //this -> sub
    console.log(sub.name);  //doggy

组合继承:

    /**3.组合继承:
     *     利用原型链实现对父类型的方法的继承
     *     借用父类型构造函数实现初始化相同属性
     */
    function Supper(name, age) {
        this.name = name;
        this.age = age;
    }
    Supper.prototype.setDate = function (date) {
        this.date = date;
    };
    function Subber(name, age, num) {
        Supper.call(this, name, age);
        this.num = num;
    }
    Subber.prototype = new Supper();  //原型链继承
    Subber.prototype.constructor = Subber;  //修正constructor
    var sub = new Subber('doggy', 18, 68);
    console.log(sub.name);  //doggy
    sub.setDate(2019);  //调用继承的方法
    console.log(sub.date);  //2019
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值