面向对象的程序设计(四)原型链继承

本文深入探讨了JavaScript中通过继承创建实例的方法及其存在的局限性,特别是通过实例化过程导致的属性和方法的共享问题。通过具体代码示例展示了在使用继承时可能遇到的问题,并提出了解决方案。
function SuperType() {
    this.property = true;
}

SuperType.prototype.getSuperValue = function () {
    return this.property;
}

function SubType() {
    this.subproperty = false;
}

//继承了SuperType
SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function () {
    return this. subproperty;
}

var instance = new SubType();
alert(instance.getSuperValue());//true

alert(instance instanceof Object);//true
alert(instance instanceof SubType);//true
alert(instance instanceof SuperType);//true

alert(Object.prototype.isPrototypeOf(instance));//true
alert(SubType.prototype.isPrototypeOf(instance));//true
alert(SuperType.prototype.isPrototypeOf(instance));//true

//SubType继承了SuperType,通过创建SuperType的实例。
//弊端1:看下面的列子,instance3的colors属性居然被instance2改变了
//弊端2:没有办法在不影响所有对象实例的情况下,给超类型构造函数(SuperType2)传递参数
function SuperType2() {
    this.colors = ["red", "blue"];
}

function SubType2() {
}

SubType2.prototype = new SuperType2();

var instance2 = new SubType2();
instance2.colors.push("black");
alert(instance2.colors);//"red", "blue", "black"

var instance3 = new SubType2();
alert(instance3.colors);//"red", "blue", "black"

 

转载于:https://www.cnblogs.com/qiangspecial/p/3175233.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值