The Declaration and implementation of the interface in JS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.