fredmarks
fredmarks

Reputation: 327

Javascript Namespaces and undefined function

Can someone explain how to do this properly

foo(); //outputs 'foo'

function foo(){
   console.log('foo');
}

but this gives 'function is undefined' error

MY_NAME_SPACE ={};

MY_NAME_SPACE.foo(); //undefined

MY_NAME_SPACE.foo = function(){
   console.log('foo');
}    

I can see that in the second example, the call was made before the function was added to the My_NAME_SPACE object, but if this is the case,how would one use this type of "name space" if the ordering is important?

Upvotes: 0

Views: 1156

Answers (1)

chester
chester

Reputation: 297

Yes, if you are going to use this namespace pattern, you will need to create and populate the namespace before trying to invoke methods or access property values that have not yet been assigned to the namespace.

Instead of defining the namespace object and then defining each consecutive method in the namespace, eg:

var MY_NAME_SPACE = {};

MY_NAME_SPACE.foo = function() {
    console.log('foo');
}

I prefer to use what is referred to as the module pattern, as the methods that I want contained in MY_NAME_SPACE are visually wrapped in the module:

var  MY_NAME_SPACE = (function () {

    var foo = function () {
        console.log('foo');
    };

    return { foo: foo };

})();


MY_NAME_SPACE.foo()

Also, if the methods you wish to wrap in a namespace or module are independent and reusable, it would makes sense to create a separate file, maybe my_name_space.js, and include this file in projects that need access to the methods in MY_NAME_SPACE (the MY_NAME_SPACE API).

Upvotes: 1

Related Questions