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
-
1No you can't, and what you have is just a regular objectadeneo– adeneo2016年03月09日 22:40:20 +00:00Commented Mar 9, 2016 at 22:40
4 Answers 4
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.
4 Comments
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;
...
Comments
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.
Comments
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.
4 Comments
=>) and this doesn't really work like a using statement. undefined, that's not entirely the problem. You can't access the members directly by name without a preceding this.. A using statment doesn't require this. so it's a close approximation but not quite right.using in the first place.