Reputation: 13
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
?!
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?!
Upvotes: 1
Views: 32
Reputation: 20899
You should probably read up on how this
works.
Declaring a variable in a local scope using var x = 16
is not the same as doing 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
. Since the local variable y
is not the same as window.y
, you get undefined.
Upvotes: 2