javascript鴨弁別式模擬インターフェース
4388 ワード
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;
this.methods = [];
for(var i = 0,len = methods.length; i < len; i++){
if(typeof methods[i] !== 'string'){
throw new Error("Interface constructor expects method names to be passed in a STRING");
}
this.methods.push(methods[i]);
}
};
//define a interface: var NewInterface = interface('NewInterface',[funa,funb...]);
Interface.ensureImplements = function(object){
if(arguments.length < 2){
throw new Error("Function Interface.ensureImplements called with" + arguments.length + "arguments,but expected at least 2.");
}
for(i = 1,len = arguments.length; i < len; i++){
var interface = arguments[i];
if(interface.constructor !== Interface){
throw new Error("Function Interface.ensureImplements expects arguments two and above to be instance of Interface.");
}
for(var j = 0,methodsLen = interface.methods.length;j < methodsLen;j++){
var method = interface.methods[j];
if(!object[method] || typeof object[method] !== 'function'){
throw new Error("Function Interface.ensureImplements:does not implement the " + interface.name + "interface.Method" + method + "was not found.");
}
}
}
}
//Interface.ensureImplements(object,interface_a,interface_b);
アヒルの弁別式の書き方はいいと思います.完成品の前に検査してから削除すればいいです.
まずインターフェースを定義します.
var NewInterface = interface('NewInterface',[funa,funb...]);
NewInterface
Interface.ensureImplements(object,interface_a,interface_b);
object 【 , javascript 】。