//接口类 var Interface = function(name,methods){ if(arguments.length != 2){ throw new Error('the interface constructor arguments must be 2 length!'); } this.name = name ; //确保methods里的元素为string类型 this.methods = [] ; for(var i = 0,len = methods.length ; i <len ; i++){ if( typeof methods[i] !== 'string'){ throw new Error('the interface\'methods name must be a string type!'); } this.methods.push(methods[i]); } } // 检测对象是否实现相应接口中定义的方法 // 若是检验经过 不作任何操做 不经过:浏览器抛出error Interface.ensureImplements = function(object,implInterfaces){ // 若是检测方法接受的参数小于2个 参数传递失败! if(arguments.length != 2 ){ throw new Error('Interface.ensureImplements method constructor arguments must be == 2!'); } // 得到接口实例对象 for(var i = 0 , len = implInterfaces.length; i<len; i++ ){ var instanceInterface = implInterfaces[i]; // 判断参数是不是接口类的类型 if(instanceInterface.constructor !== Interface){ throw new Error('the implmented Interface constructor not be Interface Class'); } // 循环接口实例对象里面的每个方法 for(var j = 0 ; j < instanceInterface.methods.length; j++){ // 用一个临时变量 接受每个方法的名字(注意是字符串) var methodName = instanceInterface.methods[j]; // object[key] 就是方法 if( !object[methodName] || typeof object[methodName] !== 'function' ){ throw new Error("the method name '" + methodName + "' is not found !"); } } } } // 二: 准备工做: // 1 实例化接口对象 var CompositeInterface = new Interface('CompositeInterface' , ['add' , 'remove']); var FormItemInterface = new Interface('FormItemInterface' , ['update','select']); // 2 具体的实现类 var CompositeImpl = function(){ //构造时即检测 Interface.ensureImplements(this,CompositeImpl.prototype.implInterfaces); } //定义要实现的接口 CompositeImpl.prototype.implInterfaces = [CompositeInterface,FormItemInterface]; // 3 实现接口的方法implements methods CompositeImpl.prototype.add = function(obj){ alert('add'); // do something ... } CompositeImpl.prototype.remove = function(obj){ alert('remove'); // do something ... } CompositeImpl.prototype.update = function(obj){ alert('update'); // do something ... } CompositeImpl.prototype.select = function(obj){ alert('select'); // do something ... } var c1 = new CompositeImpl(); c1.add();