Interface in Javascript)

Source: Internet
Author: User

I didn't expect JavaScript to be able to simulate interfaces, So I suddenly thought JavaScript was more powerful. So I extracted the content of JavaScript Design Pattern for everyone to learn. The content was slightly changed.

1. Benefits of introducing interfaces in javascript:

The interface is self-descriptive and can promote code reuse. It facilitates communication between different classes and is particularly useful in large projects. It is also conducive to code testing and debugging.

 

2. disadvantages of interface Introduction

The introduction of interfaces strengthens the role of types, reduces language flexibility, and brings additional overhead. It cannot force other programmers to abide by the interfaces you define.

 

3. Method of imitating the interface

Method 1: Describe with comments

View code

 1 /* 2   interface  composite{ 3     function add(child); 4     function remove(child); 5     function getChild(index); 6   } 7   interface FormItem{ 8     function save(); 9   } 10 */11 var CompositeForm = function(){12     ...13 }14 15 CompositeForm.prototype = {16     add: function(child){...},17     remove: function(child){...},18     getChild: function(index){...},19     save: function(){...}20 }

 

Disadvantages of this method: It mainly belongs to the scope of the program documentation and relies entirely on self-conscious compliance with interfaces.

Method 2: Use attributes to check the simulated Interface

View code

/*  interface  composite{    function add(child);    function remove(child);    function getChild(index);  }  interface FormItem{    function save();  } */  var CompositeForm = function(){     this.implementsInterfaces = ['Composite','FormItem'];     ...  }  function addForm(formInstance){    if(! implements(formInstance,'Composite','FormItem')){        throw new Error('object does not omplement a required interface');    }    ...  }    function implements(object){    for(var i=1;i<arguments.length;i++){        var interfaceName = arguments[i];        var found = false;        for(var j=0;j<object.implementsInterfaces.length;j++){            if(object.implementsInterfaces[j] === interfaceName){                found = true;                break;            }        }        if(! found){            return false;   //an interface was not found        }    }    return true;}

This method explicitly declares the interfaces It supports, but does not ensure that the class actually implements the self-claimed interfaces.

Method 3. Duck variant simulation interface

First, define the Interface Class

View code

 1 var Interface = function(name,methods){ 2     if(arguments.length != 2){ 3         throw new Error('....'); 4     } 5     this.name = name; 6     this.methods = []; 7     for(var i=1; i< methods.lenght;i++){ 8         if(typeof method[i] !== 'string'){ 9             throw new Error(...);10         } 11         this.methods.push(methods[i]);12     }13 }14 Interface.ensureImplements = function(object){15     if(arguments.length < 2){16         throw new Error(...);17     }18     for(var i=1;i<arguments.lenght;i++){19         var interfaceName = arguments[i];20         if(interfaceName.constructor !==Interface){21             throw new Error(...);22         }23         for(var j=0; j<interfaceName.methods.length;j++){24             var method = interfaceName.methods[j];25             if(!object[method] || typeof object[method] !== 'function'){26                 throw new Error(...);27             }28         }29     }30 }

Next, simulate the interface:

View code

 1 /* 2   interface  composite{ 3     function add(child); 4     function remove(child); 5     function getChild(index); 6   } 7   interface FormItem{ 8     function save(); 9   } 10 */11 var Composite = new Interface('Composition',['add','remove','getChild']);12 var FormItem = new Interface('FormItem',['save']);13 14 var CompositeForm = function(){15     ...16 }17 18 function addForm(formInstance){19     Interface.ensureImplements(formInstance,Composite,FormItem);20     ...21 }

Features: This feature ensures that the interface of the forced implementation class is implemented, but the self-description is missing. A helper class (Interface) and helper function (ensureimplements) are also required ).

 

4. Conclusion:

The best way to simulate an interface is to use both the annotation and duck variant methods. In fact, it is not the most difficult to simulate an interface. The difficulty is when to use the interface.

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.