Search code examples
javascriptoopinterfaceprototypeprototypal-inheritance

Javascript lack of Interface - simple solution with Prototype


In Javascript, in contrast to other languages which OOP like Java, do not provide interfaces. There is some solutions on the internet which are more complex than mine, but I want to share with you my way how to resolve this problem, to get some constructive critisism from you and check if I choose the right way of thinking. I choose Answer your own question – share your knowledge, Q&A-style and you will see my answer below.


Solution

  • Here is an example that uses a timeout to check if the needed functions are implemented, you can implement multiple Interfaces.

    Since JS is not a compile time type checked language you can't really have a good solution for this. Maybe you can have a look at mix ins (under mix ins), leave the default implementation or override.

    function PersonInterface(proto,fnName){
      //after running the implements function it depends how quickly you're
      //  creating instances and how quickly you implement the functions
      setTimeout(function(){
        if(typeof proto.getSurName !== 'function'){
          throw new Error(fnName + ' has to implement getSurName');
        }
        //and others if needed
      },100);
    }
    
    function implements(fn, implements,fnName){
      implements(fn.prototype,fnName);
    }
    
    function Employer(){};
    implements(Employer, PersonInterface,'Employer');
    //depends how quickly you set the getSurName
    //  and how quickly you will be creating Emplyer instances
    //  trying to call getSurName
    //  comment out the next line and you'll get 
    //   Employer has to implement getSurName
    Employer.prototype.getSurName=function(){};