Monthly Archives: November 2013

Emulate Interfaces in JavaScript with interface.js

Interfaces are something you don’t actually need in a loosely typed language like JavaScript, but sometimes it’s nice to make sure that some methods really exist. This is where interface-js comes in handy. You can create new interfaces like this:

var IAnimal = new Interface([ 'roar', 'sleep' ]);

When you are creating your class, you can use it like this:

var Tiger = function() {

  // Implement the interface 'IAnimal'
  IAnimal.implement(this);
};

Tiger.prototype.roar = function() {
  console.log('ROARRR');  
};

‘Tiger’ does not implement the method ‘sleep’, so it throws an error:

InterfaceException: Missing the following method: 'sleep'

The source code for interface-js is available on GitHub. Pull requests are welcome!