作為技術類的開篇文章,很是糾結了一番到底寫什麼的。想了想,就寫物件導向吧。。始終對於我們程式員來說,物件導向是寫一篇好文章。對不起習慣了。應該說是寫一篇好代碼的開始。
而物件導向的三大特徵中最重要的就是繼承了。
繼承現在有很多種寫法,google一下到處都是。我就不再在這裡重複了。直接上My Code吧。
核心功能代碼如下:
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 generationvar c1=new child();c1.DoSomeStaff()//output:I'm the second generationc1 instanceof parent//truec1 instanceof child//true
可以看見,我這個繼承寫法的好處在於在繼承和調用父類的時候更接近進階語言的語序和文法。使得代碼在閱讀方面有所提高。
當然這個寫法還是有一定的局限性。
例如如果進行多重繼承以後會出現只能找到最後一個父類的情況。
本文出自 “技術源於專註” 部落格,請務必保留此出處http://mt830813.blog.51cto.com/7611383/1255645
查看本欄目更多精彩內容:http://www.bianceng.cn/webkf/prototype/