接口:利 固化一部分代码 弊 丧失js的灵活性
在JavaScript中模仿接口
/*interface Composite{ function add(child); function remove(child); function getChild(index);}interface FormItem{ function save();}*/var CompositeForm=function(id,method,action){ ...};CompositeForm.prototype.add = function(child) { ...};CompositeForm.prototype.remove = function(child) { ...};CompositeForm.prototype.getChild = function(index) { ...};CompositeForm.prototype.save = function() { ...};
改进一下,用属性检查
/*interface Composite{ function add(child); function remove(child); function getChild(index);}interface FormItem{ function save();}*/var CompositeForm=function(id,method,action){ this.implementsInterfaces=['Composite','FormItem']; ...};...function addForm(formInstance){ if (!implements(formInstance,'Composite','FormItem')) { throw new Error("Object does not implement a required interface."); } ...}function implements(Object){ for(var i=1;i
用鸭式辨型模仿接口
var Composite =new Interface('Composite',['add','remove','getChild']);var FormItem=new Interface('FormItem',['save']);var CompositeForm=function(id,method,action){ ...};...function addForm(formInstance){ ensureImplements(formInstance,Composite,FormItem); ...}
结合第一种和第三种
var Composite =new Interface('Composite',['add','remove','getChild']);var FormItem=new Interface('FormItem',['save']);var CompositeForm=function(id,method,action){ ...};...function addForm(formInstance){ Interface.ensureImplements(formInstance,Composite,FormItem); ...}
Interface类的定义
var Interface=function(name,method){ if(arguments.length!=2){ throw new Error("需要2个参数"); } this.name=name; this.method=[]; for(var i=0,len=methods.length;i