JS实现继承的几种方式

本文详细探讨了JavaScript中的四种继承方式:构造函数继承、原型链继承、组合继承和寄生式组合继承。通过示例代码展示了每种方式的实现和优缺点,包括如何共享属性、调用父类方法等关键点。对于理解JavaScript的继承机制具有重要参考价值。
摘要由CSDN通过智能技术生成

1.借用构造函数继承

        //  function Animal(type) {
        //     this.type = type;
        //     this.friends=[];
        // }
        // function Cat(name){
        //     Animal.call(this)
        //     this.name = name;
        // }

        // var  cat = new Cat('蓝猫');
        // var cat1 = new Cat('喵喵');
        // cat.friends.push('蓝猫');
        // cat1.friends.push('咪咪');
        // console.log(cat.friends,cat1.friends);

2.原型链继承

// function Animal(type) {
        //     this.type = type;
        //     this.friends=[];
        // }
        // function Cat(name){
        //     this.name = name;
        // }
        // Animal.prototype.eat = function () {
        //     console.log('吃鱼')
        //   }
        // //想让猫有type属性,  Animal 放在Cat的原型链上
        
        // Cat.prototype = new Animal('cat');//animal的实例 可以使用构造函数中的属性和方法,
        //                                     //也可以使用animal原型上的属性和方法
        // var cat = new Cat('tom');
        // console.log(cat.type);
        // cat.eat()

        // //私有属性变成共享属性

        //   var  cat1 = new Cat('蓝猫');
        //   cat1.friends.push('红兔')
        //   console.log(cat.friends);

3.组合继承

//  function Animal(type) {
        //     this.type = type;
        //     this.friends=[];
        // }
        // Animal.prototype.eat = function () {
        //     console.log('吃鱼');
        //   }

          
        // function Cat(name,type){
        //     Animal.call(this,type)
        //     this.name = name;
        // }
        // Cat.prototype = new Animal();

        // var  cat = new Cat('蓝猫','中国猫');
        // var cat1 = new Cat('喵喵');
        // cat.friends.push('蓝猫');
        // cat1.friends.push('咪咪');
        // console.log(cat);
       //父类构造函数 实例属性 声明了两次

4.寄生式组合继承


        //  function Animal(type) {
        //     this.type = type;
        //     this.friends=[];
        // }
        // Animal.prototype.eat = function () {
        //     console.log('吃鱼');
        //   }


        // function Cat(name,type){
        //     Animal.call(this,type)
        //     this.name = name;
        // }
        // //只继承 父类构造函数的原型属性
        // // function Temp() {

        // //   }
        // //   Temp.prototype = Animal.prototype;
        // //   Cat.prototype = new Temp()

        // Cat.prototype = {
        //     __proto__:Animal.prototype
        // }

        // // Cat.prototype = new Animal();

        // var  cat = new Cat('蓝猫','中国猫');
        // var cat1 = new Cat('喵喵');
        // cat.friends.push('蓝猫');
        // cat1.friends.push('咪咪');
        // console.log(cat);
        //父类构造函数 实例属性 声明了两次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值