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


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 lose the capability of being used before it's defined.

链接地址: http://www.djcxy.com/p/17050.html

上一篇: )变量赋值说明

下一篇: Javascript中的命名空间问题