Closures bug?!

Giganews Newsgroups
Subject: Closures bug?!
Posted by:  Nathan.M.Sn…@gmail.com
Date: Wed, 12 Sep 2007

Why does f() === 'undefined' at the end of the following code snippet?

var f = 3;
f = function(){var f = f; return function(){return f};};
alert(f());

My understanding of closures is that the base environment of a closure
is the same as when it was created.  When invoked, the entire
environment is the parameter bindings unioned with this base
environment, and the parameter bindings would shadow the base
environment.

Therefore, the environment of the outer function is the global
environment and the environment of the inner is the environment
created by the outer.

Furthermore, each of the following examples return 3 as one would
expect.

var f = 3;
f = function(){var x = f; return function(){return x};}();
alert(f());

var f = 3;
f = function(f){return function(){return f};}(f);
alert(f());

Thanks!

Sincerely,

Nathan

Replies