Function的擴充(1):繼承

來源:互聯網
上載者:User

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

而物件導向的三大特徵中最重要的就是繼承了。

繼承現在有很多種寫法,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/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.