Search code examples
javascriptiife

Uncaught TypeError: Property 'fn' of object [object DOMWindow] is not a function


I know how to fix this error but does anyone tell me a comprehensive explanation of why this error occurs?

var fn = function () {
  return fn();
}(); //uncaught TypeError: Property 'fn' of object [object DOMWindow] is not a function

Solution

  • When you use the var keyword in the global scope, the declared variable becomes a property of the global object. In a web browser, the global object is the window object, which itself is an instance of DOMWindow(). So, using that knowledge we can rewrite your code to look like this:

    window.fn = function () {
        return window.fn();
    }();
    

    Taking away the initial assignment, we have

    (function () {
        return window.fn();
    })();
    

    ...which defines an anonymous function wherein window.fn() is called. However, at the point this code runs, window.fn is not a function (and never will be), so an exception is thrown because you're trying to invoke it even though it doesn't have an internal [[Call]] flag.

    If you take away the immediate execution of the anonymous function, then window.fn would be a function:

    var fn = function () {
        return fn();
    }
    fn(); //-> infinite loop