tags:

views:

274

answers:

4

I am bit confused with namespaces of function in javascript. Can I have function with same names?

Thanks

+10  A: 

There is no official concept of a namespace in Javascript like there is in C++. However, you can wrap functions in Javascript objects to emulate namespaces. For example, if you wanted to write a function in a "namespace" called MyNamespace, you might do the following:

var MyNamespace = {};

MyNamespace.myFunction = function(arg1, arg2) {
    // do things here
};

MyNamespace.myOtherFunction = function() {
    // do other things here
};

Then, to call those functions, you would write MyNamespace.myFunction(somearg, someotherarg); and MyNamespace.myOtherFunction();.

I should also mention that there are many different ways to do namespacing and class-like things in Javascript. My method is just one of those many.

For more discussion, you might also want to take a look at this question.

Marc W
A capital first letter usually implies that it's a constructor. It might be better to use `myNamespace` instead.
Eli Grey
I think it's just a matter of personal coding style, really. I always use first letters for class names and constructors. In this case, `MyNamespace` is acting as a class.
Marc W
A: 

http://www.dustindiaz.com/namespace-your-javascript/ has some good examples on this.

Andreas Bonini
A: 

JavaScript doesn't have the concept of namespace. If you see something like System.Array, the code is referring to an object Array that is a property of the object System.

The object System could be also a function, but a function is normally used when there is the need to allocated an object, and that function would became the object constructor.
If System.Array is a function then you could write something like

new_array = new System.Array(10, 20, 30);

The example is pretty useless, as JavaScript already has array objects.

kiamlaluno
+1  A: 

Currently, no JavaScript implementations support namespaces, if you're referring to ECMAScript 6/JavaScript 2 namespaces.

If you're referring to how namespacing is done today, it's just the use of one object and putting every method you want to define onto it.

var myNamespace = {};
myNamespace.foo = function () { /*...*/ };
myNamespace.bar = function () { /*...*/ };
Eli Grey