Saturday, November 21, 2009

Function pointers in JavaScript

What do you think the following code alerts ?

var f = function () {
    alert('Function 1');
};

var pf = f;

f = function () {
    alert('Function 2');
};

pf();

If you answered 'Function 2', then you are wrong



First, a function f was created which now occupies a block of memory. Internally, the only reference the function has is the assigned location in the JavaScript's Heap.

When you a pass a function (var pf = f;), you are only passing a pointer to a function. This means that you are passing a reference to the memory location of the function, not the function name!

In the above code, pf is a pointer to the function f created beforehand. When we later on change to original function f to point to a different function, pf still retains its pointer to the original allocated function.

The only difference now is that the variable f is now pointing to a different memory address of the Heap (because it is now pointing to a new function)