Interface: The benefits of curing part of the code cheat loss JS Flexibility
imitating interfaces in JavaScript
/* interface composite{ function Add (child); function remove (child); function Getchild (index);} Interface formitem{ function Save ();} */ var compositeform=function(id,method,action) { function(child) { function (Child) { function(index) { function() { ...};
Improve, check with attributes
/*interface composite{function Add (child); function remove (child); function Getchild (index);} Interface formitem{function Save ();}*/varcompositeform=function(id,method,action) { This. implementsinterfaces=[' Composite ', ' FormItem ']; ...}; ...functionAddForm (forminstance) {if(!implements (forminstance, ' Composite ', ' FormItem ')) { Throw NewError ("Object does not implement a required interface."); } ...}functionimplements (Object) { for(vari=1;i<arguments.length;i++){ varInterfacename=Arguments[i]; varInterfacefound=false; for(varj=0;j<object.implementsinterfaces.length;j++){ if(object.implementsinterfaces[j]==InterfaceName) {Interfacefound=true; Break; }; } if(!interfacefound) { return false; }; } return true;}
Using duck type to imitate interface
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); ...}
Combined with the first and third types of
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); ...}
Definition of the interface class
varInterface=function(name,method) {if(arguments.length!=2){ Throw NewError ("2 parameters required"); } This. name=name; This. method=[]; for(vari=0,len=methods.length;i<len;i++){ if(typeofmethods[i]== ' String '){ Throw NewError ("Need to be a string"); } This. Methods.push (Methods[i]); }};interface.ensureimplements=function(object) {if(arguments.length<2){ Throw NewError ("Minimum of 2 parameters required"); } for(vari=1,len=arguments.length;i<len;i++){ varInterface=Arguments[i]; if(interface.constructor!=Interface) { Throw NewError ("Requires 2 parameters and is an instance of interface"); } for(varj=0,methodslen=interface.methods.length;j<methodslen;j++){ varMethod=Interface.methods[j]; if(!object[method]| |typeofobject[method]!== ' function ') { Throw NewError (' Method not found '); }; } }};
JavaScript design mode 2