1. 程式人生 > >Javascript高級程序設計--讀書筆記之面向對象(二)

Javascript高級程序設計--讀書筆記之面向對象(二)

原型鏈 func pro 原型對象 ets span gre {} javascrip

前面講了面向對象的封裝,這章我們就來說一說繼承

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)
}

Javascript高級程序設計--讀書筆記之面向對象(二)