The interface of JavaScript learning __javascript

Source: Internet
Author: User

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 ();


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.