I am little bit surprised after seeing the output of below javascript code. Still I do not have clue on why myObj variables have not been used inside own method. If I want to use myObj varaibles, what should be the way?
// The use of the "this" object inside the setTimeout function refers to the Window object, not to myObj
var highValue = 200;
var constantVal = 2;
var myObj = {
highValue: 20,
constantVal: 5,
calculateIt: function () {
setTimeout (function () {
console.log(this.constantVal * this.highValue);
}, 2000);
}
}
myObj.calculateIt(); // 400
//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.
答案 0 :(得分:1)
because this
inside setTimeout
is referring to global window
context. Create a local variable, often named 'self', in the correct scope instead.
var highValue = 200;
var constantVal = 2;
var myObj = {
highValue: 20,
constantVal: 5,
calculateIt: function () {
var self = this;
setTimeout (function () {
console.log(self.constantVal * self.highValue);
}, 2000);
}
}
myObj.calculateIt(); // 400