setTimeout Variables are Executed in the Global Scope?
JavaScript
var highValue = 200;
var constantVal = 2;
var myObj = {
highValue: 20,
constantVal: 5,
calculateIt: function () {
setTimeout (function () {
var x= this.constantVal * this.highValue;
console.log("this.constantVal: "+this.constantVal);
console.log("x: "+x);
}, 2000);
}
}
// The "this" object in the setTimeout function used the global highValue and constantVal variables, because the reference to "this" in the setTimeout function refers to the global window object, not to the myObj object as we might expect.
myObj.calculateIt() // 400