问题描述
我试图更好地理解this
的用法.在尝试此代码时,我发现可以使用类似console.log(this.arr[4])
的方式访问arr
中的项目,但前提是必须使用var
声明arr
.如果我使用let
或const
声明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.
推荐答案
在浏览器中,顶级this
是window
,顶级var
声明也使变量可以作为window
的属性进行访问,而let
和const
则没有.引用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`的用法.该示例很冗长,但其目的是为了更好地理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!