Variable defined with Let/const is not "identified" by this

Asked

Viewed 48 times

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 the this as a mechanism to access variables is only possible in some situations (which tend to become less common with the advancement of language).

  • Aside from the this can be modified in Runtime using methods such as call or apply, which makes this approach extremely unreliable and error-prone.

  • but the variable does not turn a property of the global object?

  • myFunc’s call-site is the global object, so this would be the global object, why doesn’t it work with Let?

  • The marked duplicate question answers this - see this answer. In short, var and let have different behaviors when it comes to this. I reiterate what I said in my previous comment: the function of this does not refer to scope, but yes to the context. It’s different. So much so that the new language features (such as let) 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.

1 answer

1

When you access "this.name", you are actually accessing "window.name" (outside the context of an object, "this" is simply the window).

The keyword "var" in the global scope adds the variable as attribute of the "window" object, while the keyword "Let" does not add.

There are some other differences between Let/const and var, described in this article: https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/

  • why Let/const does not add to the global object?

  • I believe the idea is to prevent a "distant" part of the program, outside the context from which the variable was created, from touching its content. The following is a long description of the differences between Let and var, which go beyond the specific case of your question: https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.