Jaggler3
Jaggler3

Reputation: 304

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

Upvotes: 0

Views: 1016

Answers (4)

Izkata
Izkata

Reputation: 9313

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.

Upvotes: 2

TheToolBox
TheToolBox

Reputation: 272

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.

Upvotes: 0

leviathon
leviathon

Reputation: 51

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.

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

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;
...

Upvotes: 1

Related Questions