什麼是接口?接口是為了完成某一種任務、功能或目的,所規定的一些原則。在程式設計中,由於任務都是透過函數(方法)來完成的,所以程式裡的接口通常就是「規定好有幾個方法、方法名叫什麼」。
而JavaScript中的接口,是把某個「類型對象」的實例與「接口對象」做比對,若符合規則(即該對象是否擁有接口中規定的所有方法名與數量),就說這個對象實現了規定的接口。接口類則是用來實例化出不同接口(即不同的方法組合)的工具。
生活化的例子:電話類下面可以有「座機」、「手機」、「平板電話」等子類,它們都有一個共同任務——「撥通電話」。為此我們可以規定:無論哪個子類,其實例化的對象要實現「撥通電話」,必須具備兩個方法:1. 按出號碼;2. 按撥號鍵。
以下是固定的設計模式:
var Interface = function(name, methods){
if(arguments.length != 2){
throw new Error("Interface constructor called with " + arguments.length + " arguments, but expected exactly 2.");
}
this.name = name;
this.methods = [];
for(var i = 0, len = methods.length; i < len; i++){
if(typeof methods[i] !== 'string'){
throw new Error("接口方法的名稱必須是一個字符串");
}
this.methods.push(methods[i]);
}
};
// 靜態類方法:檢查對象是否實現了指定接口
Interface.ensureImplements = function(){
if(arguments.length < 2){
throw new Error("方法 Interface.ensureImplements 至少期望 2 個參數。");
}
for(var i = 1, len = arguments.length; i < len; i++){
var _interface = arguments[i];
if(_interface.constructor !== Interface){
throw new Error("接口,不是通過 Interface 類實例出來的");
}
// 取出接口中的方法名,逐一驗證對象是否擁有同名方法
for(var j = 0, methodsLen = _interface.methods.length; j < methodsLen; j++){
var method = _interface.methods[j];
if(!arguments[0][method] || typeof arguments[0][method] !== 'function'){
throw new Error("Interface.ensureImplements: 對象的方法 " + method + " 找不到或不是一個 Function");
}
}
}
};
使用範例:
// 透過接口類實例化一個「撥通電話」接口,規定 callfun 與 callnum 兩個方法
var testInterface = new Interface("call", ["callfun", "callnum"]);
// 行動電話類的構造函數
var mobilephone = function(call){
this.name = call;
};
// 行動電話類的公有方法(方法名必須與接口規定一致)
mobilephone.prototype = {
"constructor": mobilephone,
"callfun": function(){ document.write("按鍵"); },
"callnum": function(){ document.write("拔號"); }
};
// 實例化一個手機對象
var anycall = new mobilephone("anycall");
// 驗證該對象是否實現了「撥通電話」接口
Interface.ensureImplements(anycall, testInterface);
anycall.callnum();
透過 Interface.ensureImplements 這個靜態方法,我們就能在執行期檢查某個對象是否具備接口所要求的全部方法,這是JavaScript模擬接口的經典做法。