Implementation of object-oriented interface in JavaScript __javascript

Source: Internet
Author: User
Tags instance method

Interfaces are the foundation of object-oriented programming, a set of data structures that contain functional methods, and, like classes, are more abstract concepts in programming languages. For example, in the life of the interface, set-top box, people use it to achieve watching different channels and signals of the program, it is like the different types of information collection and encapsulation of the equipment, and finally the various types of information into the television can be recognized information. An interface in a programming language is actually a package of different classes and provides a unified external contact channel so that other objects can invoke the members of different classes using the interface.

--from the beginning to the mastery of jquery development


The concept of an interface
Constructors (classes) are specific implementations, and interfaces are conventions of classes. API interface (application interface), human-computer interface, power interface, USB interface, etc., although different uses, functions vary, but all contain a common characteristics: conventions, specifications. It can be said that the interface is a contract and contract, it agreed to the designers and users must follow the requirements. The interface promises specific classes that should be prior to the function. As a very necessary example, implement an interface in Java, such as the following code:

Interface base{
  void Function1 ();
  void Function2 ();
  void Function3 ();
}
The base interface promises 3 basic functions: Function1 (), function2 (), Function3 (). This interface is like a contract between party a (calling the user of the Class) and party B (the developer who defines the class). Party B is responsible for realizing the function of interface agreement. The realization of the function is called class. The following example:
Class App implements base   //define an app class that uses this class to implement interface base
Class app will follow the conventions of the interface. Professionally, the application class app inherits the base interface class. Its specific implementation is as follows:
Class APP implements base{
  void Function1 () {
    System.out.println ("I am Fun1");
  }
  void Function2 () {
    System.out.println ("I am Fun2");
  }
  void Function3 () {
    System.out.println ("I am Fun3");
  }
In this way, party B realizes this interface, and party A should also follow the agreement of the interface to use the class app on the line. So, the interface (interface) and Class (class) are actually the same data structures. In an interface, you can declare a property, method, event, type, but not a variable, and you cannot set the specific value (function implementation) of the declared member. That is, an interface can only define members and cannot assign values to defined members. An interface, as a convention for its inheriting or derived classes, inherits the implementation of interface properties, methods, events, and types by inheriting classes or derived classes. Consistency should be maintained between the interface and the implementation class, whether the method name or the property invocation order.
The purpose of the interface is to constrain coding, and to promote code specification, which is necessary for strongly typed language and is also a very important link. But for JavaScript weak-type languages, strict type checking can constrain JavaScript flexibility. Many front-end developers do not use interfaces at all, but do not affect the design of scripts. Benefits of using interfaces: Reduce the coupling between objects and increase the flexibility of the code. Learning to use interfaces to make the hands of the functions more agile, which is important in large-scale development.
For JavaScript, it does not natively support interface functionality and does not provide built-in methods. However, a manual design of an additional interface program will have an impact on the performance of the program. The larger the project, the greater the overhead. Therefore, using the interface can follow two conditions: ① project size, if a framework, the use of interfaces to some extent, improve the performance of the program. If it's a simple application, you don't have to use an interface. ② If you are more proficient with JavaScript interfaces, you can also use multiple interfaces, and if you are concerned about using interfaces to affect performance, you can either clear the interface function module or set the interface's execution conditions before considering the release of the product. Prevents it from being executed frequently, affecting performance.

implementation of the interface
The interface is not supported in JavaScript, but we can mimic other languages to define the interface. The following is to plan the design and implementation of the interface structure: (1) Design an interface-assisted class structure, which is equivalent to a filter used to detect the legality of initialization parameters during interface instantiation. If the interface design criteria are met, then the number of each method name and parameter in the 2nd parameter is entered into the interface internal property methods as an array element. Each parameter type is checked for compliance before input. At the same time check whether the parameters are defective, and immediately to 0 completion parameters.
function Interface (name,methods) {//Interface helper class, which includes the name of the interface instance and the method set   if (arguments.length!=2) {//If the number of parameters is not equal to 2, throws an exception.
    throw new Error (' standard interface agreement, requires two parameters ');  }   this.name = name; Stores the first parameter value, instantiated by the interface instance name   This.methods = [];
Interface instance method memory   if (Methods.length < 1) {//If the second argument has an element number of 0, the description is an empty array and throws an exception.
    throw new Error (' second parameter of interface cannot be null ');  }   for (var i = 0; i < methods.length i++) {//Start traversal detection for elements of the 2nd parameter     var item = methods[i]; &nbs P   if (typeof item[0]!== ' string ') {//if the first element of the second argument is not of type string, throws an exception       throw new Error (the first parameter of the interface convention should be
As a string ");    }     if (item[1]&&typeof item[1]!== ' number ') {//If the second argument has a second element and the second element is not a number type, throw an exception &N Bsp
    throw new Error (' the first parameter of the interface agreement should be numeric ');    }     if (item.length = 1) {//If the second parameter has only one element, then manually add the second element to it 0       item[1] = 0; &nb Sp  }     This.methods.push (item);
Store the specified method in the array memory. &nbsP }
}
(2) Defines a method implements for the interface helper class Interface, which detects that the implementation class conforms to the interface instance's convention. It contains at least two parameters, and the 1th argument o represents the implementation class, and the 2nd parameter and subsequent arguments represent the interface standards that the class will implement. That is, you can specify multiple interface conventions for a class, which makes it more flexible to design interface instances. Then iterate through the second and all subsequent parameters, in the circular structure, the first cleaning of the toilet interface is an instance of the interface standard, otherwise it will throw an exception. Then, we read the method name from the method memory of the interface instance, and fill in the class to verify that the method of the class conforms to the standard of the interface instance setting, and the validation includes the method name, function type and number of parameters. If there is a problem, throw the exception immediately.
interface.implements = function (o) { //The Convention for detecting whether a class method conforms to an interface instance, where O, in the future, will be the this   if ( ARGUMENTS.LENGTH<2) {//detect whether the value passed by this method conforms to the rules     throw new Error (the interface contract class should contain at least two parameters.)
");   }   for (var i=1;i<arguments.length; i++) {//Traversal detection class to follow the instance is legal     var interface = Arguments[i];
Here interface represents an instance object of an interface.     if (Interface.constructor!== interface) {      throw new Error (' from the 2nd parameter must be an interface instance ');   &N Bsp }     for (Var j=0;j<interface.methods.length;j++) {//test class method conforms to interface instance's convention       var methods = inte
RFACE.METHODS[J][0];       if (!o[method] | | typeof O[method]!== ' function ' | | o[method].length!==interface.methods[j][1]) {&NB Sp
      throw new Error ("The implementation class failed to perform" + Interface.name + "interface Method" + Methods + "convention");      }    }  } 
(3) Instantiate the interface standard, the Interface interface is only a constructor, that is, a framework agreement, there is no specific standard that the class should follow. In the framework agreement, the monitoring logic has been designed, and once the interface is instantiated and the conventions that the class should follow, the class that applies the instance of the standard must be kept. The following defines 6 concrete interface instances based on the interface interface standard.
Set the different implementation instances of the interface
var get = new Interface (' Get ', [[' Get ', 0]]);
var set = new Interface ("Set", [["Set", 1]]);
var saying = new Interface ("saying", [["saying", 1]]);
var base = new Interface ("base", [["Get", 0],["set", 1]]);
var Base1 = new Interface ("Base1", [["Set", 1],["get", 0]]);
var Base2 = new Interface ("Base2", [["Get", 0],["set", 1],["saying", 1]);
(4) Define the standards that should be implemented in the class, that is, the interface conventions that the class should follow.
Create a wooden Donkey class
function Neddy () {
  this.name = ';
  Interface.implements (This,base,get,set); Let the wooden donkey class implement an instance of an interface, you can specify multiple, or you can have only one.
}
Define two methods according to the interface instance get,set
Neddy.prototype.get = function () {return
  this.name;
}
Neddy.prototype.set = function (name) {
  this.name = name;
}
(5) Set up a number of interface instances in the class, we are testing
The detection interface realizes
var Neddy = new Neddy ();
Neddy.set ("testing");
Console.log (Neddy.get ()); Testing
Successfully completed the application of the interface, here, if in the Neddy class, we let it implement the interface instance and Neddy.prototype in the method defined to the class is not uniform, or interface and interface conflict between, will throw an exception. For example, we can modify the interface implementation in Neddy, and then add an interface instance BASE2, we will report an exception, because we do not follow the protocol of the interface, to Neddy add saying () method.
The above example is only using JS to simulate the implementation of interface functions, in the actual development, we need to according to different needs, the development of different interfaces.

Extended knowledge: The parameter list of the instrumentation function is generally three different forms
①arguments.callee.length
② the name of the function. length
③arguments.length
Among them ① and ② are the same, ③ depending on the specific situation.
The definition of a generic function declaration has a default property name inherited from Object, for example:
  function fn (x,y) {
    console.log (fn.name);//FN
    Console.log (arguments.callee.name);//FN
    Console.log ( Fn.length); 2
    Console.log (arguments.callee.length);//2
    Console.log (arguments.length);//To be determined by the specific situation
  }
  fn ( 1,2,3); OUTPUT FN fn 2 2 3 respectively
In order to illustrate the o[method].length of the above interface detection parameter length, examples are as follows:
function A () {}
A.prototype.say = function (x,y,z,o) {}
var a = new A ();
Console.log (a[' say '].length); 4
Related Article

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.