Function的擴展(1):繼承

作爲技術類的開篇文章,很是糾結了一番到底寫什麼的。想了想,就寫面向對象吧。。始終對於我們程序員來說,面向對象是寫一篇好文章。對不起習慣了。應該說是寫一篇好代碼的開始。

而面向對象的三大特徵中最重要的就是繼承了。

繼承現在有很多種寫法,google一下到處都是。我就不再在這裏重複了。直接上我的代碼吧。

核心功能代碼如下:

Function.prototype.Implement = function (parentType) {
    //判斷父類是否存在以及是否爲可繼承類型
    if (parentType != undefined && typeof (parentType) == "function") {
        var temp = this.prototype;
        this.prototype = new parentType();
        for (var i in temp) {
            this.prototype[i] = temp[i];
        }
        this.prototype.base = parentType.prototype;
    }
}

核心功能有了。讓我們來測試一下在js中傳統繼承所具有的特徵吧。

先聲明父類

var parent= function () {
    //constructor
}
parent.prototype = (function () {
    //private
    return {
        //public
        SomeVar:"I'm the first generation"
        DoSomeStaff:function(){
           console.write(this.SomeVar);
        }
    };
})();

這裏對大家進行一下推薦。這種類的聲明方法。

可以通過我的註釋看到。有構造方法。有私有方法。有公有方法。

然後我們聲明一下繼承類


var child= function () {
    //constructor
}
child.prototype = (function () {
    //private
    return {
        SomeVar:"I'm the second generation"
        DoSomeStaff:function(){
           this.base.DoSomeStaff.call(this);//調用父類的方法
        }
    };
})();
//這裏表示child繼承了parent
//是不是比傳統的寫法要更符合高級語言的語序?
child.Implement(parent)


然後我們進行測試


var p1=new parent();
p1.DoSomeStaff()//output:I'm the first generation
var c1=new child();
c1.DoSomeStaff()//output:I'm the second generation
c1 instanceof parent//true
c1 instanceof child//true


可以看見,我這個繼承寫法的好處在於在繼承和調用父類的時候更接近高級語言的語序和語法。使得代碼在閱讀方面有所提高。


當然這個寫法還是有一定的侷限性。

例如如果進行多重繼承以後會出現只能找到最後一個父類的情況。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章