user6793397 user6793397 - 1 year ago 80
Javascript Question

Namespacing issue in Javascript

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


function surprise() {

and this is the same function with namespacing:

var namespace = {};


namespace.surprise = function () {

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download