0
When I perform a direct function of the global scope that references any property through the this
using var
the variable is displayed correctly, but when I declare the variable with let/const
the value is undefined
, why does this occur? I thought it might be Hoisting, but I run the function after the variable already has its value assigned.
Example:
function myFunc() {
console.log(this.name)
}
var name = 'MEU NOME';
console.log(myFunc()) // MEU NOME;
--
function myFunc() {
console.log(this.name)
}
let name = 'MEU NOME';
console.log(myFunc()) // undefined
The
this
should be used to refer to an execution context, not the scope of the execution. Use thethis
as a mechanism to access variables is only possible in some situations (which tend to become less common with the advancement of language).– Luiz Felipe
Aside from the
this
can be modified in Runtime using methods such ascall
orapply
, which makes this approach extremely unreliable and error-prone.– Luiz Felipe
but the variable does not turn a property of the global object?
– Thiago
myFunc’s call-site is the global object, so this would be the global object, why doesn’t it work with Let?
– Thiago
The marked duplicate question answers this - see this answer. In short,
var
andlet
have different behaviors when it comes tothis
. I reiterate what I said in my previous comment: the function ofthis
does not refer to scope, but yes to the context. It’s different. So much so that the new language features (such aslet
) leave this behavior (old and meaningless) behind. Again I urge you to read carefully the questions marked as duplicate, since these details of JS are particularly confusing.– Luiz Felipe