Strange script overriding function pointer variable

Consider this simple scenario:

(function x(){
  var foo = function(){
    console.log('foo is alive!');

    // set 'foo' variable to an empty function, using a delay
    setTimeout(function(){
      foo = function(){};
    },0);
  }

  foo();
  // calling 'foo' again, after it should be an empty function
  setTimeout(foo,100);
})();

If you copy and run this code in your console, it will output foo is alive!twice. I am trying to figure out why it would foonot be overridden by an empty function. foois clearly a variable that is recognized inside a timeout callback that points to a function.

Boring background to this question:
This is a simple test case for a more complex scenario, which I encounter using AJAX callbacks instead of the timeout used in this simple example.

+4
source share
1 answer

setTimeout() , foo(), ( ), , setTimeout().

:

setTimeout(function () {
    foo();
}, 100);

(: http://jsfiddle.net/0p7fgsso/)

foo() , . console.log -ged.

+6

All Articles