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

randomed16
  • 13
  • 2

1 Answers1

2

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.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
  • @mr-llama Why `window.y` ?! i thought `this` is pointing to defined scope using IIFE not `window`, so what's can access all declared variables using `var` in IIFE scope?! – randomed16 Jun 09 '15 at 21:43
  • @rf7 - [Give it a shot.](https://jsfiddle.net/045nspx6/) Check your browser's console for the results. – Mr. Llama Jun 09 '15 at 21:47
  • @mr-llama Oops! it seems `this` is referring to the `window`, but IIFE is a new scope; is there any way to see all of declared variables (with `var`) inside new scope just like `console.log(this);` for `window`?! – randomed16 Jun 09 '15 at 21:51
  • @rf7 - [Nope](http://stackoverflow.com/a/2051693/477563), not programmatically at least. :( – Mr. Llama Jun 09 '15 at 21:57