user6793397 user6793397 - 3 months ago 9
Javascript Question

Namespacing issue in Javascript

I'm trying to convert a regular function into function with namespacing. This is the regular function:

surprise();

function surprise() {
alert('TEST');
}


and this is the same function with namespacing:

var namespace = {};

namespace.surprise();

namespace.surprise = function () {
alert('TEST');
};


I get the following error:
Uncaught TypeError: namespace.surprise is not a function

Answer

If you call before a function is defined, you will get a TypeError. You must defined the function first. Before you define it, the namespace does not have a surprise function, and once you call it, JavaScript doesn't know what you're talking about.

The reason why normal functions do not need to be defined first is because:

The function statement is magic and causes its identifier to be bound before anything in its code-block* is executed.

That's from here. function statements must be defined with the function keyword and not stored in a variable like this:

var myFunc = function () {
    ...
}

To be treated in the described way above. Since namespaces store the function into a variable, they lost the capability of being used before it's defined.