Now I have a module which follows a long chain of namespaces, for example:
TOP.middle.realModuleName = function () { /*...*/ }
I need to use this module on a page, and I'm not sure if this page has included the namespace Top.middle. So I would have to do something like:
if (typeof TOP !== 'undefined' && TOP.middle && TOP.middle.realdModuleName) {
new TOP.middle.realModuleName();
}
I think the if
statement looks really long and verbose. Anyone has suggestions on how to write a nicer parameter checking pattern for this case?
JavaScript “namespace” is a programming paradigm that is utilized for assigning scope to the identifiers such as variables and function names. It is used to prevent collisions between the same-named variables and functions.
Namespaces are a TypeScript-specific way to organize code. Namespaces are simply named JavaScript objects in the global namespace. This makes namespaces a very simple construct to use. Unlike modules, they can span multiple files, and can be concatenated using outFile .
The namespace is a way which is used for logical grouping of functionalities. It encapsulates the features and objects that share common relationships. It allows us to organize our code in a much cleaner way. A namespace is also known as internal modules.
Namespace is a context for identifiers, a logical grouping of names used in a program. Within the same context and same scope, an identifier must uniquely identify an entity. In an operating system a directory is a namespace.
Try this simple helper function:
function exists(namespace) {
var tokens = namespace.split('.');
return tokens.reduce(function(prev, curr) {
return (typeof prev == "undefined") ? prev : prev[curr];
}, window);
}
It takes a String
as input and will return the object if it exists. You can use it like this:
var module = exists("TOP.middle.realModuleName");
For example:
exists("noexist"); // returns undefined
exists("window"); // returns DOMWindow
exists("window.innerHeight"); // returns Number
exists("window.innerHeight.toString"); // returns Function
exists("window.innerHeight.noexist"); // returns undefined
It also works properly for expressions that evaluate to false:
testNum = 0;
testBool = false;
testNull = null;
exists("testNum"); // returns 0
exists("testBool"); // returns false
exists("testNull"); // returns null
just encapsulate it in a TRY/CATCH?
try {
return new TOP.middle.blablabla();
}
catch(err) {
// oh no!
}
return null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With