JavaScript 继承

本文介绍了JavaScript中几种常见的继承方式,包括原型链、借用构造函数、共享原型及圣杯模式,并通过示例代码展示了每种模式的特点及其限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承发展史

1.传统形式 –>原型链
- 过多继承了没用的东西
2.借用构造函数 –>call/apply
- 不能继承借用构造函数的原型,原型还是自己的
- 每次构造函数都要多走一个函数,造成运行复杂
3.共享原型
- 不能随便改动自己的原型,不能实现自己个性化的原型
示例:

<script type = "text/javascript"> 
    Father.prototype.lastName = "Deng";
    function Father(){
    }
    function Son() {
    }
    function inherit(Target,Origin) {
        Target.prototype = Origin.prototype;
    }

    inherit(Son,Father);
    Son.prototype.sex = "male";         //此时给Son添加一个属性,这个属性也会添加到Father上
    var son = new Son();                //因为此时他俩指向同一个原型,所以我们说不能实现元素的个性化设计
    var father = new Father();
</script>

4.圣杯模式

    Father.prototype
    function F() {}
    F.prototype = Father.porotype
    Son.prototype = new F();   //这时先继承再生成新的new,又满足了继承,又不会互相干扰

代码示例:

<script type = "text/javascript"> 
    function inherit(Target,Origin)function F() {
        F.prototype = Father.prototype;
        Target.prototype = new F();
        Target.prototype.constructor = Target;
        Target.prototype.uber = Target;   //构造对象的超类(真正继承自谁)
    }
    Father.prototype.lastName = "Deng";
    function Father(){
    }
    function Son() {
    }
    inherit(Son,Father);
    var son = new Son();
    var father = new Father();
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值