接⼝
在JS这种弱类型的语⾔中,类型不匹配错误很难跟踪。可以使⽤接⼝来进⾏类型检
查。如果强制使⽤,⼜会弱化语⾔的灵活性。因为有额外的代码调⽤,所以⼜会降低性能。
解决⽅法就是在开发时进⾏类型检查,在开始完成后删除此部分代码。
但JS中的接⼝实现⽅式是模拟的,它以⽂档和⽅法检查相结合。缺点在于它只检查⽅
法的名称,并不检查参数的名称,类型,数量以及⽅法的返回值。
var Interface = function(name, methods) {
if(arguments.length != 2) {
throw new Error("Interface constructor 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("Interface constructor expects method names is
String.");
}
this.methods.push(methods[i]);
}
};
Interface.ensureImplements = function(object) {
if(arguments.length < 2) {
throw new Error("Interface.ensureImplements exactly arguments at least
2.");
}
for(var i = 1, len = arguments.length; i < len; i++) {
var interface = arguments[i];
if(interface.constructor !== Interface) {
throw new Error(interface + "exactly type is 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: object "
+ "does not implement the " + interface.name
+ " interface. Method " + method + " was not found.");
}
}
}
};
//模拟使⽤
//定义了接⼝Person0和Person1,并在每个接⼝中定义三个⽅法
var Interface0 = new Interface('Person0', ['add', 'del', 'getItem']);
var Interface1 = new Interface('Person1', ['add', 'del', 'getItem']);
function addForm(myClassInstance){
//⽤来检查myClassInstance是否实现了接⼝Interface0和Interface1
Interface.ensureImplements(myClassInstance, Interface0, Interface1)
}