简体   繁体   中英

Using Namespace in JavaScript

I have a namespace Utilities in JavaScript, it looks sort of like this:

var Utilities = Utilities || {
    printTest: function() { print("test"); }
}

I can call my printTest function with Utilities.printTest(); but I am wondering if I can call it with something like

var Utilities.....
using Utilities;
printTest();

I want it to work similar to how C++ implements namespaces into your code with the using statement. Is there anything similar for JavaScript?

Thanks

The with statement :

var a, x, y;
var r = 10;

with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}

Note that it is not allowed in strict mode.

Nope, that's not possible. The closest you can get (assuming the this context isn't important) is assigning the functions to individual variables.

var printTest = Utilities.printTest;
var otherMethod = Utilities.otherMethod;
...

There is no 'using' keyword in JavaScript like there is in C# or other languages.

You can pull in the module or library via a script tag for the client. Node.js has a 'require' keyword that will you can use in your Node.js application like this: require("body-parser");

You can put that statement at the top of a file and Node.js will look up your file structure for that module. It's methods are then available in that file.

The following would give something of a similar functionality (when this is defined), but there's a reason using is infrequently used in C++: It oftentimes defeats the purpose of having a namespace in the first place. Namespaces exist to isolate independent parts of a design, and if they need to be mashed together like this, it might be worth considering a different structure. That being said, there's a reason the keyword exists, so there are certainly legitimate uses!

function using(namespace) {
  if (typeof namespace === 'object' && this !== null && this !== undefined) {
    for (var i in namespace) {
      this[i] = namespace[i]
    }
  }
}

using.bind(this,myNamespace);//attaches the values of namespace to this

Again, this pattern isn't really recommended for most cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM