Can anyone explain namespace in javascript with an example?

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

Thanks


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.


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 () { /*...*/ };
链接地址: http://www.djcxy.com/p/17038.html

上一篇: 需要建议... JavaScript OOP /命名空间

下一篇: 任何人都可以用一个例子来解释JavaScript中的命名空间?