I'm trying to better understand the use of `th

2019-08-27 16:57发布

问题:

This question already has an answer here:

  • Do let statements create properties on the global object? 5 answers
  • why don't const and let statements get defined on the window object [duplicate] 2 answers

I'm trying to better understand the use of this. In experimenting with this code, I found I can access the items in arr by using something like console.log(this.arr[4]), but only if arr is declared using var. If I declare arr using let or const, I get a TypeError.

First, I do understand this is verbose. Like I said, I am just experimenting to try and get a better understanding and came across this issue that piqued my curiosity.

const arr = [
  1,
  false,
  {
    name: 'John',
    address: '123 Peachtree Drive'
  },
  function(name = 'new user') {
    const greeting = 'Hello there, '
    console.log(greeting + name)
  },
  'foo',
]

console.log(this.arr[4])

Again, if I simply declare arr using var instead of let I can log it just fine.

回答1:

In a browser, top-level this is window, and top-level var declarations also make variables accessible as properties of window, while let and const do not. The correct way to reference arr is simply

console.log(arr[4])

I would discourage you from using top-level this to even access var declarations, because code which relies on that behavior of var is obviously confusing, as this case is a perfect example of.



回答2:

The behavior you're getting confused about is not specific to 'this'. It is related to scope. 'var' has a different scope than 'let' or 'const'.

var - has function level scoping and can change the value reference
let - has block level scoping and can change the value reference
const - has block level scoping but cannot change the value reference

https://love2dev.com/blog/javaScript-var-let-const/

Be precise about how and where you declare your variables as this is an important part of JavaScript syntax/interpretation.