Implementation of object-oriented interface in JavaScript

Source: Internet
Author: User
Tags instance method

Interfaces are the basis for object-oriented programming. It is a set of data structures that include a functional approach, as with classes. are more abstract concepts in programming languages. For example, the interface in life. Stb. It is used to achieve programs that watch different channels and signals, and it is like a device for assembling and encapsulating different types of information. Finally, various types of information are converted into the information that can be recognized by TV. Interfaces in programming languages are actually encapsulated in different classes and provide a uniform external contact channel so that other objects can use interfaces to invoke members of different classes.

--from the start to the mastery of jquery development


the concept of interfaces
Constructors (classes) are detailed implementations, and interfaces are the conventions of classes.

API interface (application interface), human-computer interface, power interface, USB interface, etc., although the use of different functions. But all include a common feature: Conventions, specifications.

To be able to say that the interface is a contract and contracts, it agreed with the designers and users must follow the requirements. The interface promises that the detailed class should be pre-functional. To take a very necessary example, implement the interface in Java, for example, 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. The contract is between party a (the user calling the class) and party B (the developer of the definition Class). Party B is responsible for implementing the interface Convention function. The implementation of a function is called a class. Examples include the following:

Class App implements base   //define an app class to implement the interface base with this class
The class app will follow the conventions of the interface.

Professionally, it is. The App class app inherits the base interface class. Its detailed implementation is for example the following:

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");}  }
Such Party B realizes this interface, and party A should also come to use the class app according to the agreement of the interface. So. Interfaces (interface) and classes (Class). are actually the same data structure.

The ability to declare properties, methods, and events in an interface. Type, but cannot declare a variable and cannot set the detailed value of the declared member (feature implementation).

In other words, an interface can only define members. You cannot assign a value to a defined member. An interface is an implementation of an interface property, method, event, type, as the contract of its inheriting or derived class. Both the method name and the property invocation order should be consistent between the interface and the implementation class.


The purpose of the interface is to constrain the encoding. Promote code specification. is required for strongly typed languages. is also a very important link.

However, for JavaScript weakly typed languages, strict type checking can bind JavaScript's flexibility. Very many front-end developers do not use interfaces at all, but do not affect the design of scripts. Advantages of using interfaces: Reduce the coupling between objects and increase the flexibility of the code. Learning to use interfaces can make the functions in your hands smarter, which is important in large-scale development.
For JavaScript, it does not natively support interface functionality and does not provide built-in methods. However, the artificial design of an additional interface program, but also on the performance of the program has an impact.

The larger the project. The greater the overhead.

So, with no interface can follow two conditions: ① project size, the assumption is a framework, the use of interfaces to some extent will improve the performance of the program.

Assuming it's a simple application, you don't have to use an interface. ② assumes that the JavaScript interface is more proficient, and that multiple interfaces are available. Assuming that you worry too much about using the interface to affect performance, you can clear the interface function module before considering the product announcement. or set the operating conditions of the interface.

Prevent it from being run frequently. Affect performance.



Implementation of the interface
Interfaces are not supported in JavaScript. But we are able to imitate other languages to define interfaces.

To plan the design of the interface structure and the realization of the detection function: (1) Design an interface-aided class structure, which is equivalent to a filter. Used to check if the initialization parameters are legitimate during interface instantiation. Assuming that the interface design criteria are met, enter the interface internal attribute methods as an array element for each method name and number of parameters in the 2nd parameter.

Before inputting, each parameter type is checked to see if it meets the requirements.

At the same time, check if there is a defect, and immediately 0 to complement the parameters.

function Interface (name,methods) {//Interface helper class, which contains the name of the interface instance and the method set if (arguments.length!=2) {//assuming that the number of parameters is not equal to 2, throws an exception.

throw new Error (' Standard interface convention '.  two parameters required); } this.name = name; Stores the first participant value, which is the name of the interface instance after instantiation this.methods = []; Interface instance method memory if (Methods.length < 1) {//Assuming the number of elements of the second parameter is 0, the description is an empty array.    Throws an exception.  throw new Error (' the second parameter of an interface cannot be null ');    } for (var i = 0; i < methods.length; i++) {//starts traversing the element of the 2nd parameter to detect var item = Methods[i];    if (typeof item[0]!== ' string ') {//assuming that the first element of the second parameter is not of type string, throw an exception throw new Error ("the first parameter of the interface convention should be a string"); } if (item[1]&&typeof item[1]!== ' number ') {//Assuming the second parameter has a second element, and the second element is not a number type, throws an exception throw new Error (' interface convention    The number of references should be numeric '); } if (item.length = = 1) {//Assume that the second parameter has only one element.    Then manually add a second element to it 0 item[1] = 0; } this.methods.push (item); Store the specified method in the array memory.

}}

(2) Define a method implements for the interface helper class Interface, which will detect whether the implementation class conforms to the contract of the interface instance.

It contains at least two parameters, and the 1th parameter, O, represents an implementation class. The 2nd parameter and its subsequent parameters represent the interface standards that the class will implement. That is, the ability to specify multiple interface conventions for a class allows for a more flexible classification of design interface instances. It then iterates through the second and subsequent parameters, in the loop structure, whether the flushing interface is an instance of the interface standard, or an exception is thrown.

Then from the method memory of the interface instance, read the method name one by one, fill in the class to verify whether the method of the class conforms to the standard of the interface instance setting, and verify that it contains the method name, function type and number of parameters. If there is a problem, throw the exception immediately.

Interface.imple ments = function (o) { //is used to check whether the class method conforms to the contract of the interface instance. The O in the future will be the this  if (arguments.length<2) in the class {//Check if the value passed by this method conforms to the specified     throw new Error ("The interface contract class should include at least two parameters. "); }  for (Var i=1;i<arguments.length; i++) {//traverse the check class to follow the instance is legal     var interface = arguments[i];//Here The interface represents an instance object of the interface. 

    if (Interface.constructor!== interface) {      throw new Error (' from 2nd to above must be an instance of an interface ') );   }    for (var j=0;j<interface.methods.length;j++) {//Check if class methods conform to interface instance Conventions       var method = interface.methods[j][0];      if (!o[method] | | typeof O[method]!== ' function ' | | o[method].le NGTH!==INTERFACE.METHODS[J][1]) {        throw new Error ("The implementation class failed to perform" + Interface.name + "interface Methods" + method + "Convention");     }   } }}

(3) Instantiate interface standard, Interface interface but a constructor, which is a framework protocol, does not have a detailed standard that the class should follow. Framework protocol. The monitoring logic has been designed, once the interface is instantiated. and specifies the conventions that the class should abide by, then the class that applies the instance of the standard must be kept. The following defines 6 detailed interface instances according to 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 Inter Face ("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 criteria in the class that should be implemented, that is, the interface conventions that classes 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 the interface, can specify more than one. can also have just one. }//defines two methods according to an interface instance Get,setneddy.prototype.get = function () {  return this.name;} Neddy.prototype.set = function (name) {  this.name = name;}
(5) Multiple interface instances are set in the class. Let's check it out.
The detection interface realizes var Neddy = new Neddy (); Neddy.set ("testing"); Console.log (Neddy.get ()); Testing
Successful completion of the application of the interface, here, assume that in the Neddy class, we let it implement the interface instance and Neddy.prototype to the class defined method is not uniform, or interface and interface conflict, will throw an exception. For example, we can change the interface implementation in Neddy. Add an interface instance Base2 to it and it will report an exception. Since we do not follow the protocol of the interface, add the saying () method to Neddy.
The above example is only to use JS to simulate the implementation of interface functions, in the actual development, we need to base on different needs, the development of different interfaces.

Extended knowledge: There are generally three forms of the list of check function
①arguments.callee.length
② function name. length
③arguments.length
Among them ① and ② are the same, ③ depending on the details of the situation.


The definition of a general function declaration has a default property name inherits from Object, with the following proportions:

  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);//Depending on the details  }  fn ( (a); OUTPUT FN fn 2 2 3 respectively
In order to illustrate the problem of the above interface detection length o[method].length, the ratio is as follows:
function A () {}a.prototype.say = function (x,y,z,o) {}var a = new A (); Console.log (a[' say '].length); 4

Object-oriented interface implementation in JavaScript

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.