Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nicer way of checking JavaScript namespace

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?

like image 686
Grace Shao Avatar asked Oct 03 '11 18:10

Grace Shao


People also ask

What is a JavaScript namespace?

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.

What is namespace in node JS?

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 .

What is namespace in TypeScript?

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.

What is a website namespace?

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.


2 Answers

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
like image 119
Peter Avatar answered Oct 01 '22 11:10

Peter


just encapsulate it in a TRY/CATCH?

try {
    return new TOP.middle.blablabla();
}
catch(err) {
    // oh no!
}

return null;
like image 39
Matthew Avatar answered Oct 01 '22 12:10

Matthew