`.call()`

by Chad Drummond

JavaScript

// Using `.call()` to change context

function People() {
  this.people = []
}

People.prototype.add = function(count) {
  for (var i = 0; i < count; i++) {
    this.people.push(new Person())
  }
}

function Person(name) {
  this.name = name || 'The Dude'
}

var people = new People()
people.add(4)
var peopleObj = { people: [] }
// Use the `People()` instance to call `add()`
//   setting `this` to `peopleObj`
people.add.call(peopleObj, 2)

console.log(people, peopleObj)