Javascript高级程序设计--读书笔记之面向对象(二)

前面讲了面向对象的封装,这章我们就来说一说继承

1.原型链

实现原型链有一种基本模式,其代码大概如下

<script>
    function SuperType(){
        this.property = true
    }
    SuperType.prototype.getSuperValue = function(){
        return this.property;
    }
    function SubType(){
        this.subproperty = false
    }
    //继承了 SuperType
    SubType.prototype = new SuperType()
    SuperType.prototype.getSubValue = function(){
        return this.subproperty
    }
    var instance = new SubType()
    alert(instance.getSuperValue())   /true
</script>

以上代码定义了两个类型,SuperType 和SubType 每个类型分别有一个属性和方法,SubType继承了SuperType,实现的本质是重写原型对象

原型链虽然很强大,可以用它来实现继承,但是也存在一些问题,引用类型的值会被的原型属性会被所有实例共享,通过下面代码说明问题

    //原型链的问题
    function SuperType(){
        this.colors = ["red", "blue", "green"]
    }
    function SubType(){}
    //继承了SuperType
    SubType.prototype = new SuperType()
    var instance1 = new SubType()
    instance1.colors.push("black")
    alert(instance1.colors)   //"red", "blue", "green","black"
    var instance2 = new SubType()
    alert(instance2.colors)   //"red", "blue", "green","black"

  2.组合继承

function SuperType(name){
    this.name = name;
    this.colors = ['red', 'blue', 'green'];
}
SuperType.prototype.sayName = function(){
    alert(this.name);
}
function SubType( name, age){
    //继承属性
    SuperType.call(this, name)
    this.age= age
} 
//继承方法
SubType.prototype = new SuperType()
SubType.prototype.constructor = SubType
SubType.prototype.sayAge = function(){
    alert(this.age)
}

猜你喜欢

转载自www.cnblogs.com/Qqqing/p/10663117.html