Quick Guide to using interfaces with JavaScript

Kameron Tanseli
Dec 19, 2016 · 1 min read

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); // inherit
Checkbox.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

Kameron Tanseli

Written by

Senior Front End Engineer at Flux, 19.

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade