js中原型链分析,对象的组合继承,使子类继承父类的属性和方法

当不同的构造函数具有相同的属性和方法时,为减少代码的重复,实现代码重用,可以借用构造函数,继承其他构造函数中的属性或方法。
如下面例子:
主要步骤:
1、在子类中使用Perent.call(this,arg1,arg2);来借用父类的构造函数,使用call方法改变this指向的当前子类的对象,并将其参数传递给父类的构造函数,此时子类中就有了父类的属性。
2、要继承父类的方法,改变子类原型对象,Child.prototype=new Perent();将子类构造函数的原型对象指向父类的对象,根据下面实例进行分析其原型链:
dog对象(包含age,color,leg,name,weight属性)其原型指向—>Animate对象(含有name,age,leg,weight属性,其构造函数为Dog)—>Animate原型对象(含有定义的desc()方法和run()方法,,其构造函数为Animate)—>Object原型对象(含有toString等方法,其构造函数为Object)
注意: 要修改构造器为其原本的构造函数,否则会指向Animate构造函数
Dog.prototype.constructor=Dog;
具体其原型链打印效果如下图:
在这里插入图片描述
实例代码如下:

 function Animate(name,leg,age,weight) {
        this.name=name;
        this.leg=leg;
        this.age=age;
        this.weight=weight;
    }
    Animate.prototype.run=function () {
        console.log(this.name+'会跑');
    }
    Animate.prototype.desc=function () {
        if(this.color!=''){
            console.log('这是一只'+this.age+'岁的'+this.color+this.name);
        }else{
            console.log('这是一只'+this.age+'岁的'+this.name);
        }
    }
    function Dog(name,leg,age,weight,color) {
        //借用Animate构造函数,this指向当前构造函数new的对象
        Animate.call(this,name,leg,age,weight);
        this.color=color;
    }
    //将Dog构造函数的原型对象设置为Animate对象,这样就可以继承Animate原型对象上的方法
    Dog.prototype=new Animate();
    //注意要修改构造器为其原本的构造函数,否则会指向Animate构造函数
    Dog.prototype.constructor=Dog;
    var dog1=new Dog('柴犬',4,3,20,'黄色');
    console.dir(dog1);
    console.log(dog1.name);
    dog1.desc();

打印结果:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值