To implement an interface, you must implement all the methods in the interface.
function Interface (NAME,FNS) {//declares an interface class
THIS.name = name;
This.methods=[];
for (Var i=0;i<fns.length;i++) {
if (typeof fns[i]! = ' string ')
throw new Error ("Method name must be string, must pass string array");
This.methods.push (Fns[i]);
}
}
var Face1 = new Interface (' Face1 ', [' Add ', ' edit ']);/Create an interface object that declares two methods that need to be implemented add and edit
var face2 = new Interface (' Face2 ', [' del ', ' Save ']);
interface.ensureimplements = function (obj) {//defines the functions that detect whether an interface is implemented and can pass one or more interface objects
if (arguments.length<2) {
throw new Error ("at least two parameters must be passed");
}
for (Var i=1;i<arguments.length;i++) {
if (arguments[i].constructor! = Interface) {
throw new Error ("This is not an interface object, please pass the interface object");
}
for (Var j=0;j<arguments[i].methods.length;j++) {
if (! ( OBJ[ARGUMENTS[I].METHODS[J]) | | typeof Obj[arguments[i].methods[j]]! = ' function ') {
throw new Error ("All methods in the interface are not implemented");
}
}
}
}
function dd () {//Declare all methods of a class to implement an interface
This.name= "yes";
This.add=function () {
}
This.del=function () {}
This.edit=function () {}
This.save=function () {}
}
var KK = new DD ();
Interface.ensureimplements (KK,FACE1,FACE2);//detects if the KK object implements Face1 and Face2 two interfaces
In general, if the parameters of one class are objects of another class, we use interface technology.
function Demo (KK) {
Interface.ensureimplements (KK,FACE1,FACE2);
This.formaction = kk;//passes the object of the DD class to the FormAction property of the demo class.
}
Demo.prototype.operation = function () {
var sdata = This.formaction.save ();
}
The Declaration and implementation of the interface in JS