简体   繁体   中英

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 ?!

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?!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM