做爲技術類的開篇文章,非常糾結了一番到底寫什麼的。想了想,就寫面向對象吧。。始終對於咱們程序員來講,面向對象是寫一篇好文章。對不起習慣了。應該說是寫一篇好代碼的開始。程序員
而面向對象的三大特徵中最重要的就是繼承了。ide
繼承如今有不少種寫法,google一下處處都是。我就再也不在這裏重複了。直接上個人代碼吧。測試
核心功能代碼以下:this
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中傳統繼承所具備的特徵吧。google
先聲明父類
prototype
var parent= function () { //constructor } parent.prototype = (function () { //private return { //public SomeVar:"I'm the first generation" DoSomeStaff:function(){ console.write(this.SomeVar); } }; })();
這裏對你們進行一下推薦。這種類的聲明方法。
對象
能夠經過個人註釋看到。有構造方法。有私有方法。有公有方法。繼承
而後咱們聲明一下繼承類
it
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)
而後咱們進行測試io
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
能夠看見,我這個繼承寫法的好處在於在繼承和調用父類的時候更接近高級語言的語序和語法。使得代碼在閱讀方面有所提升。
固然這個寫法仍是有必定的侷限性。
例如若是進行多重繼承之後會出現只能找到最後一個父類的狀況。