vsync
vsync

Reputation: 130391

Weird scenario with function pointer variable override

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 would copy and run this code in your console, it would output foo is alive! twice. I am trying to understand why wouldn't foo gets overridden with the empty function. foo is clearly a variable which is being recognized inside the timeout callback, which points to the function.

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

Upvotes: 4

Views: 65

Answers (1)

bardzusny
bardzusny

Reputation: 3828

You're launching setTimeout() function right away, passing it foo() while it still exists (is not empty), therefore it is actually available later, within the scope of setTimeout().

Quick demo to achieve your expected result:

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

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

Here the foo() function is accessed only after it becomes an empty function. So nothing gets console.log-ged.

Upvotes: 6

Related Questions