js继承-寄生组合继承

文章展示了如何使用JavaScript中的原型链实现对象继承,通过clone函数将parent构造函数的属性和方法传递给Child构造函数,同时Child可以添加自己的特性。测试部分创建了Child实例并打印其属性和方法的值。
摘要由CSDN通过智能技术生成
function clone(parent,child) {
        child.prototype = Object.create(parent.prototype)
        child.prototype.constructor = child
    }
    function parent(){
        this.name = 'name'
    }
    parent.prototype.getName = function(){
        return this.name
    }

    function Child(){
        parent.call(this)
        this.name2 = 'name2'
    }
    clone(parent,Child)
    Child.prototype.getName2 = function(){
        return this.name2
    }

测试

let child = new Child()
    console.log(child);
    console.log(child.getName());
    console.log(child.getName2());

测试结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值