var Interface = function(name, methods){
if(arguments.length != 2){
throw new Error("Interface constructor called with " + arguments.length + " argument, but expected exactly 2.");
}
this.name = name;
this.methods = [];
for(var i = 0, l = methods.length; i < l; i++){
if(typeof methods[i] !== "string"){
throw new Error("Interface constructor expects method names to be passed in as a string");
}
this.methods.push(methods[i]);
}
}
Interface.ensureImplements = function(obj){
if(arguments.length < 2){
throw new Error("Function Interface.ensureImplements called with " +
arguments.length + " argument, but expected at least 2.");
}
for(var i = 1, l = arguments.length; i < l; i++){
var interface = arguments[i];
if(interface.constructor !== Interface){
throw new Error("Function Interface.ensureImplements expects arguments two and above to be instances of Interface.");
}
for(var j = 0, len = interface.methods.length ; j < len; j++){
var method = interface.methods[j];
if(!obj[method] || typeof obj[method] !== 'function'){
throw new Error("Function Interface.ensureImplements: object "
+ "does not implement the " + interface.name
+ " interface. Method " + method + " was not found.");
}
}
}
}
It might seem like interfaces reduce JavaScript’s flexibility, but they actually improve it by allowing
your objects to be more loosely coupled.
posted on 2009-03-16 21:42
汪杰 阅读(252)
评论(0) 编辑 收藏 引用 所属分类:
javascript