JAVASCRIPT面向对象的程序设计之借用构造函数实现继承

借用构造函数实现继承

由于通过原型链方式实现继承会存在缺陷(参考原型链继承), 所以有了借用构造函数实现继承。

借用构造函数实现方式如下:

function SuperType() {
    this.colors = ["red", "blue", "green"];
}

function SubType() {
    SuperType.call(this);
}

var instance1 = new SubType();
instance1.colors.push("black");  //"red", "blue", "green", "black"
console.log(instance1.colors);

var instance2 = new SubType();
console.log(instance2.colors);  //"red", "blue", "green"

通过在SubType构造函数中调用SuperType的call方法实现继承;

通过借用构造函数实现继承还可以向超类构造函数传递参数, 原型链继承不能向超类构造函数传递参数, 如下:

function SuperType(name) {
    this.colors = ["red", "blue", "green"];
    this.name = name;
}

function SubType(name, age) {
    SuperType.call(this, name);
    this.age = age;
}

var instance1 = new SubType("Nicholas", 29);
console.log(instance1.name);  //Nicholas
console.log(instance1.age);  //29

此时, SubType将拥有SuperType所拥有的属性和方法。

但是通过借用构造函数实现继承时,SuperType原型对象中的属性和方法不会被继承, 如下。

function SuperType() {
    this.colors = ["red", "blue", "green"];
    this.getColors = function() {
        return this.colors;
    }
}

SuperType.prototype.getSuperColors = function() {
    return this.colors;
}

SuperType.prototype.name = "Nicholas";

function SubType() {
    SuperType.call(this);
}

var instance1 = new SuperType();
console.log(instance1.getSuperColors());  //"red", "blue", "green"
console.log(instance1.name);  //"Nicholas"
console.log(instance1.getSuperColors());  //"red", "blue", "green"

var instance2 = new SubType();
console.log(instance2.getColors());  //"red", "blue", "green"
console.log(instance2.name);   //undefined
console.log(instance2.getSuperColors());  //报错, 没有该方法

其中方法getColors方法是在SuperType构造函数中定义的, 所以SubType继承了,可以正常调用, 但是getSuperColors方法则是在SuperType的原型对象中定义的, 不能被继承;属性也是一样。

因为借用构造函数实现继承也有缺陷,所以有了组合继承。

备注: 例子及截图均来自《JAVASCRIPT高级程序设计:第3版》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值