[英]Access declared variables via `this` in non-global scopes
var x = 16;
console.log(this["x"]); // 16
我可以接受,但是:
(function () {
var y = 16;
console.log(this["y"]); // undefined
}());
为什么我们不能通过this
访问变量?
我知道当我们赋值时是可能的,例如:
(function () {
x = 16; // will assigned as `this["x"] = 16`
console.log(x); // 16;
}());
非全局范围的var
问题是什么?
你应该如何读了this
工作。
使用var x = 16
在局部范围内声明变量与执行this.x = 16
。 前一个示例只是一个局部变量,后者会影响局部上下文。
你的例子:
(function () {
var y = 16;
console.log(this["y"]); // undefined
}());
这将设置一个名为y
的局部变量,但随后会在当前上下文(可能是window.y
定义y
。 由于局部变量y
与window.y
,您将得到未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.