Search code examples
javascriptecmascript-5name-binding

Why does the function name inside a named function in JavaScript no longer refer to the function itself?


Consider the following named function:

function f() {
    return f.apply(this, arguments);
}

If you call this function normally it would result in a stack overflow as expected. Not very interesting. So let's do some magic:

var g = f, f = alert;

Now if you call f it will simply alert the first argument. However if you call g it will still alert the first argument. What's happening? Shouldn't calling g result in a stack overflow?

What I understand is that inside the function f (now g) the variable f is no longer bound to f. It becomes a free variable. Hence inside f the variable f now points to alert.

Why does this happen? I would expect the function name inside a named function to always refer to the function itself. I'm not complaining. It's actually pretty cool. I'm just curious.


Solution

  • When you do:

    var g = f
    

    This is effectively the same as:

    var g = function () {
        return f.apply(this, arguments);
    }
    

    However, since you reassigned f it no longer points to the original function, it now points to alert. Looks like it's working as designed.