Before everyone started using => all over the place, it was expected that we understood how scope changed throughout a JS app. It used to be one of my favorite areas to ask about during interviews.

Here’s a little cheatsheet for understanding WTF this is.

Star

Function

When called as a function, scope is the same as call site.

function boop () {
  // this is the same as the call site
}

boop()

Method

When called as a method, scope is the object the method is defined on.

const turtle = {
  beep () {
    // this is turtle
  },
}

turtle.beep()

Constructor

Within a constructor (called with new), scope is the new object.

function Lasagna () {
  // this is the new Lasagna instance
}

new Lasagna()

Prototype

Within a prototype method, scope is the instance.

Internally, this is about the same as the method example.

Tomato.prototype.dice = function () {
  // this is the Tomato instance
}

const tomato = new Tomato()
tomato.dice()

Call/Apply

When called with call/apply, scope is defined manually.

const eyes = {
  color: 'green',
  getColor: function () {
    return this.color
  },
}

const littleRedCorvette = {
  color: 'more maroon, actually',
}

eyes.getColor() // 'green'
eyes.getColor.apply(littleRedCorvette) // 'more maroon, actually'

Summary

In practice, it doesn’t seem to come up a lot any more, but if it does, that should help. Now get your fat arrows off my lawn!