As shown in the code below, I used var value = 1
, and the value obtained is 1 . I can understand this because return this.value
here the this points to the window, so I can print out the global variable value.
var value = 1;
let obj = {
getValue: function() {
return function() {
return this.value;
}
}
}
console.log(obj.getValue()()); // 1
But if I use let to declare the value, I can't get the value of the value, the print is undefined. This is very puzzled, whether it is using let, or var statement, value is a global variable. Why is there such a difference?
let value = 1;
let obj = {
getValue: function() {
return function() {
return this.value;
}
}
}
console.log(obj.getValue()()); // undefined
Do you know why? Can you tell me? Thank you very much.