js 類建立的 三種方式

來源:互聯網
上載者:User

標籤:des   io   ar   os   使用   sp   java   on   bs   

第一種方式:  簡單的 JavaScript 類(使用Factory 方法)

  1. 首先 通過原型繼承建立一個對象

第二種方式: 使用建構函式來定義

/**原型對象是類的唯一標識:  *  若且唯若兩個對象繼承自同一個原型對象時, 它們才屬於對一個類的執行個體. *  而建構函式則不能作為類的標識, 兩個建構函式的prototype屬性可能指向同一個原型對象,  *  那麼這兩個建構函式建立的執行個體就屬於同一個類. * */
function Range(from, to){     this.from = from;    this.to = from;};
Range.prototype = {      includes : function(x){return this.from <= x && x <=this.to;},     toString : function(){return "("+this.from + "----"+this.to+")";}};var r = range(1,3);r.includes(2);console(r);
/** * 實際上 instanceof 並不會檢車 r 是否是 有 Range() 建構函式初始化而來的, * 而會檢查r 是否繼承自 Range.prototype */
r instanceof Range //如果r繼承自 Range.prototype, 則返回true;



 



 

      

    

js 類建立的 三種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.