I'm trying to better understand the use of `this`. The example is verbose, but its for the purpose of trying to better understand [duplicate]

房东的猫 提交于 2019-12-11 17:08:54

问题


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.



来源:https://stackoverflow.com/questions/56908194/im-trying-to-better-understand-the-use-of-this-the-example-is-verbose-but-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!