class Dog {
  constructor() {
    this.sound = 'woof'
  }
  talk() {
    console.log(this.sound)
  }
}
const sniffles = new Dog()
sniffles.talk(); // 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(sniffles.talk)  // breaks

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

$('button.myButton').click(sniffles.talk.bind) 

Or you could do this

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

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()
sniffles.talk() // 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

Advertisements