class Dog {
  constructor() {
    this.sound = 'woof'
  talk() {
const sniffles = new Dog(); // outputs 'woof'

Problem with the above class is that as soon as you use it somewhere else, you get a different this.

$('button.myButton').click(  // breaks

The way to fix this is to bind the ‘this’ to be sniffles.


Or you could do this

$('button.myButton').click( _ => )

A better way – function factories

In JavaScript we don’t have to use classes. Instead we can use factory functions.

Here dog is simply a function.

const dog = () => {

  const sound = 'woof'
  return {
    talk: () => console.log(sound)

const sniffles = dog() // woof

This is just a variable, ‘sound’, and then return a simple object literal with one property ‘talk’. And because of closures the talk function has access to the variable sound.

This also has the added benefit in that variable sound is private. No one else can see it except this function.

So the advantages here are:
– privateness of variables
– no explicit bind necessary
– and no magical ‘this’ to worry about because it’s all constructed in the right way