7

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

Thanks

Josh
  • 1,749
  • 3
  • 13
  • 14

2 Answers2

18

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.

Community
  • 1
  • 1
Marc W
  • 19,083
  • 4
  • 59
  • 71
  • 5
    A capital first letter usually implies that it's a constructor. It might be better to use `myNamespace` instead. – Eli Grey Dec 19 '09 at 23:17
  • 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 Dec 19 '09 at 23:19
2

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
  • 35,104
  • 14
  • 75
  • 93