任何人都可以用javascript来解释javascript中的命名空间吗?

Jos*_*osh 7 javascript

我对javascript中函数的命名空间感到困惑.我可以使用相同名称的功能吗?

谢谢

Mar*_*c W 18

在Javascript中没有像C++中那样的官方命名空间概念.但是,您可以将函数包装在Javascript对象中以模拟名称空间.例如,如果要在调用的"命名空间"中编写函数MyNamespace,则可以执行以下操作:

var MyNamespace = {};

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

MyNamespace.myOtherFunction = function() {
    // do other things here
};
Run Code Online (Sandbox Code Playgroud)

然后,要调用这些函数,你会写MyNamespace.myFunction(somearg, someotherarg);MyNamespace.myOtherFunction();.

我还应该提到,在Javascript中有许多不同的方法来执行命名空间和类类事物.我的方法只是其中之一.

有关更多讨论,您可能还想查看问题.

  • 首字母通常意味着它是一个构造函数.使用`myNamespace`可能更好. (5认同)