当不同的构造函数具有相同的属性和方法时,为减少代码的重复,实现代码重用,可以借用构造函数,继承其他构造函数中的属性或方法。
如下面例子:
主要步骤:
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();
打印结果: