Duck-type discrimination method to implement JavaScript interface:
Ya Shi Bian Li method to implement interface//interface inspection, to be able to verify the implementation of an interface, and interface all the methods//Definition interface object var Interface = function (Interfacename,methodarray
{if (Arguments.length < 2) {throw new Error (' The instance of interface constructor must be 2 length ');
} this.name = InterfaceName;
This.methods = [];
var length = Methodarray.length; for (var i = 0; i < length i + +) {if (typeof Methodarray[i]!= ' string ') {throw new Error (' The Interface met
Hod name is error! ');
} this.methods.push (Methodarray[i]);
}//Declare interface instance var compositinterface = new Interface ("Compositinterface", ["Add", "edit"]);
var formiteminterface = new Interface ("Formiteminterface", ["Delete", "select"]); Defines the implementation class that implements the two interfaces var interfaceimp = function () {} InterfaceImp.prototype.add = function () {} interfaceimp. Prototype.edit = function () {} InterfaceImp.prototype.delete = function () {}//Intefaceimp.prototyp
E.select = function () {//}
Verify that the interface instance implements all of the methods of the interface interface.ensureimplements = function (object) {if (Arguments.length < 2) {throw new
Error ("interface test method, parameters can not be less than 2");
for (var i = 1; i < arguments.length i++) {var tmpinterface = arguments[i];
for (var j = 0, length = tmpInterface.methods.length J < length; J + +) {var methodname = tmpinterface.methods[j]; if (!object[methodname] | | typeof object[methodname]!= ' function ') {throw new Error (Object.constructor.name +
"No interface" + Tmpinterface.name + "method" + methodname);
}} return true;
var instance = new Interfaceimp ();
Interface.ensureimplements (Instance,compositinterface,formiteminterface); Instance.add ();