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.
At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example: Scopping rules MDN
var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined
As MDN explains:
At the top level of programs and functions,
let
, unlikevar
, does not create a property on the global object.
This is because let
always creates a lexically scoped variable. If it were to create properties of a global object instead, those properties would be visible to code in other scopes. They wouldn't be lexically scoped anymore, defeating the point of using let
.
If you're wondering how there can be "other scopes" not lexically contained within the global scope, there can be multiple script files. Or look at this variation of your example:
let getValue = function() {
return this.value;
};
let value = 1;
console.log(getValue());
Using var value = 1;
this would still output 1
. But with let
it outputs undefined
because the function is defined lexically outside the block in which value
was declared, so it can't access it, even by going through the global object.
Or as MDN puts it:
let
allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.
That's let
's purpose for which it was designed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With