What is `this`?

by Chad Drummond

JavaScript

// # What is `this`?

// By default it refers to the current scope

function Person() {
  // `this` refers to this instance of `Person()`
  this.name = 'The Dude'
}

// Even when it's nested

function People(count) {
  // `this` refers to this instance of `People()`
  this.people = []

  // New scope, new `this`
  function Person(name) {
    // `this` refers to this instance of `Person()`
    this.name = name || 'The Dude'
  }

  for (var i = 0; i < count; i++) {
    this.people.push(new Person('Person ' + i))
  }
}