本文介绍了我试图更好地理解`this`的用法.该示例很冗长,但其目的是为了更好地理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更好地理解this的用法.在尝试此代码时,我发现可以使用类似console.log(this.arr[4])的方式访问arr中的项目,但前提是必须使用var声明arr.如果我使用letconst声明arr,则会收到TypeError.

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])

同样,如果我只是简单地使用var而不是let声明arr,我就可以很好地记录它.

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

推荐答案

在浏览器中,顶级thiswindow,顶级var声明也使变量可以作为window的属性进行访问,而letconst则没有.引用arr的正确方法很简单

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])

我不鼓励您使用顶级this甚至访问var声明,因为依赖var行为的代码显然令人困惑,因为这种情况是一个很好的例子.

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.

这篇关于我试图更好地理解`this`的用法.该示例很冗长,但其目的是为了更好地理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:23
查看更多