[英]Access declared variables via `this` in non-global scopes
var x = 16;
console.log(this["x"]); // 16
I'm ok with this, but: 我可以接受,但是:
(function () {
var y = 16;
console.log(this["y"]); // undefined
}());
Why we cant access variables via this
?! 为什么我们不能通过this
访问变量?
I know it's possibe when we assign values, for example: 我知道当我们赋值时是可能的,例如:
(function () {
x = 16; // will assigned as `this["x"] = 16`
console.log(x); // 16;
}());
What's var
problem with non-global scopes?! 非全局范围的var
问题是什么?
You should probably read up on how this
works. 你应该如何读了this
工作。
Declaring a variable in a local scope using var x = 16
is not the same as doing this.x = 16
. 使用var x = 16
在局部范围内声明变量与执行this.x = 16
。 The former example is just a local variable, the latter affects the local context. 前一个示例只是一个局部变量,后者会影响局部上下文。
Your example: 你的例子:
(function () {
var y = 16;
console.log(this["y"]); // undefined
}());
That sets a local variable called y
, but then looks for y
as defined in the current context, probably window.y
. 这将设置一个名为y
的局部变量,但随后会在当前上下文(可能是window.y
定义y
。 Since the local variable y
is not the same as window.y
, you get undefined. 由于局部变量y
与window.y
,您将得到未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.