Quick Guide to using interfaces with JavaScript

Interfaces are great for when you need to enforce some rules about how a developer builds a class. For example we have a Form class, this class is composed of lots of Fields/Inputs. Instead of writing logic to handle all different types of inputs we can define a common interface between them all.

Our Interface will contain a render() method to render out the input and a value() method to get the input?s value.

var required = function(){ throw new Error(“Implement!”); };var InputInterface = { render: required, value: required};

We can apply the Interface to a Base Input class so that all of our derived classes have the Interface.

function Input(){}Input.prototype = Object.create(InputInterface);

Now whenever you call render() you will get an Implementation Error. This forces the developer to override the Base class?s methods. Thus you have forced them to implement the interface.

function Checkbox(){ this.$el = $(“<input/>”, { type: “checkbox” }); }Checkbox.prototype = Object.create(Input); // inheritCheckbox.prototype.render = function(){ return this.$el; };Checkbox.prototype.value = function(){ return this.$el.prop(“checked”); // override methods};

If you have any questions regarding this article, you can find me on Instagram: kameron_tanseli

24