javascript scope pitfall with setTimeout and bind

Viewed 945

For the following code, I'm expecting "Jupiter" for the console 2 and 3, but getting the one bound to the global window object, even though I passed a different context.

function otherScope () {
  this.sectionHeight = "Jupiter"
}

(function () {
    var sectionHeight = "Mars";
    (function () {
      setTimeout(function () {
        console.log('console 1', sectionHeight)
      })
    }())
}())

window.sectionHeight = "cool!";

(function () {
  setTimeout(function () {
    console.log('console 2', sectionHeight)
  })
}.bind(otherScope)())


setTimeout(function () {
  console.log('console 3', sectionHeight)
}.bind(otherScope))


setTimeout(function () {
  console.log('console 4', sectionHeight)
})

3 Answers
Related