Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript scope pitfall with setTimeout and bind

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)
})
like image 628
punkbit Avatar asked Jun 24 '26 17:06

punkbit


2 Answers

Te otherScope is a function and is not a Object with properties. You have to do a new for this. So:

var x = new otherScope();
x.sectionHeight;

Next, the scope of this only reaches the current scope. The setTimeout creates a new scope. Therefor we need to do another binding. Or creating a variable inside the first scope outside the setTimeout.

Some example (variable within scope):

(function () {
  var theScope = this;
  setTimeout(function () {
    console.log('console 2', theScope.sectionHeight)
  });
}.bind(new otherScope())())

Some example (another bind):

(function () {
  setTimeout(function () {
    console.log('console 2', this.sectionHeight)
  }.bind(this)); // Pass the context to the new scope
}.bind(new otherScope())())
like image 103
Niels Avatar answered Jun 27 '26 05:06

Niels


bind sets the value of this for the function on which it is called (which I shall refer to as x).

It does not:

  • Affect anything about a different function (y) even if y is called by x
  • Affect the variables that are in scope for x or any function called by x.

There is no way to change the scope that a function exists in. That is determined solely by where it is declared.

like image 23
Quentin Avatar answered Jun 27 '26 07:06

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!