0
var tempOut = false;
var foo = function () {
    this.tempIn = false;

    this.counter = function () {
        setTimeout(function () {
            this.tempIn = true;
            tempOut = true;
        },5000);
    };
};

var myFunction = new foo();
myFunction.counter();
console.log(tempOut+ " " + myFunction.tempIn);

Hey there, I have a simple code that changes variables after 5 seconds. There are 2 variables: one global(tempOut) and one local (tempIn). When I create object from function foo, and start counter function after 5 seconds both variables should be set to true, but only tempOut changes. What I do wrong?

Humberd
  • 2,794
  • 3
  • 20
  • 37

1 Answers1

1

Change your code to this:

var foo = function () {
    this.tempIn = false;
    var me = this;
    this.counter = function () {
        setTimeout(function () {
            me.tempIn = true;
            tempOut = true;
        },5000);
    };
};

Your "this" context is not pointing at the right object, in a browser it references window inside a setTimeout.

Have a look at this, scope is a bit mindbending in JS: http://ryanmorr.com/understanding-scope-and-context-in-javascript/

garryp
  • 5,508
  • 1
  • 29
  • 41