JavaScript學習之介面__JavaScript

來源:互聯網
上載者:User

鴨式辨型法實現JavaScript介面:

//ya shi bian li 法實現介面//介面檢驗,要能夠檢驗是否實現個介面,及介面中所有的方法//定義介面對象var Interface = function(interfacename,methodArray){if(arguments.length < 2){throw new Error('the instance of interface constructor must be 2 length');}this.name = interfacename;this.methods = [];var length = methodArray.length;for(var i = 0 ; i < length; i ++){if(typeof methodArray[i] != 'string'){throw new Error('the Interface method name is error!');}this.methods.push(methodArray[i]);}}//聲明介面執行個體var CompositInterface = new Interface("CompositInterface",["add","edit"]); var FormItemInterface = new Interface("FormItemInterface",["delete","select"]);//定義實作類別,實現這兩個介面var InterfaceImp = function(){}InterfaceImp.prototype.add = function(){}InterfaceImp.prototype.edit = function(){}InterfaceImp.prototype.delete = function(){}// IntefaceImp.prototype.select = function(){// }//檢驗介面執行個體是否實現 介面的所有方法Interface.ensureImplements = function(object){if(arguments.length < 2){throw new Error("介面檢驗的方法,參數不能少於2");}for(var i = 1; i < arguments.length; i++){var tmpInterface = arguments[i];for(var j = 0, length = tmpInterface.methods.length; j < length; j++){var methodName = tmpInterface.methods[j];if(!object[methodName] || typeof object[methodName] != 'function'){throw new Error(object.constructor.name + "沒有實現介面" + tmpInterface.name +"的方法" + methodName);}}}return true;}var instance = new InterfaceImp();Interface.ensureImplements(instance,CompositInterface,FormItemInterface);instance.add();


相關文章

聯繫我們

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