Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript best practice define variable (namespace) check is not already defined

Tags:

javascript

Wanted to get opinions from the experts, I am declaring a variable that will act as the namespace for my application javascript code, but i want to check it is not already defined.

this code is terse and 'seems' to work - any reason I should avoid this and use typeof 'undef' checking instead?

var MY_NAMESPACE = MY_NAMESPACE || {};

Thanks

like image 504
house9 Avatar asked Dec 09 '10 17:12

house9


People also ask

How do you declare namespace in JavaScript?

In the Object Literal Notation, JavaScript namespaces can only be specified once, and only within that namespace may function be written. With a colon between each pair of keys and values, this may be compared to an object with a collection of key-value pairs, where keys can also stand in for new namespaces.

How do you handle variables not defined?

The usual way to declarate variables is const , let and var statements, plus the function and class declaration statements. Contrary, a variable is not defined when it hasn't been declared in the current scope using a declaration statement. The scope sets the limits where the variable is defined and accessible.

How do you declare namespace?

Declaring namespaces and namespace membersTypically, you declare a namespace in a header file. If your function implementations are in a separate file, then qualify the function names, as in this example. A namespace can be declared in multiple blocks in a single file, and in multiple files.

Does JavaScript support namespace?

JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.


1 Answers

This is the standard way of doing it. See Matt Snider's analysis of the YUI YAHOO.namespace function which uses this same check (Also for a look at how to make it easy to create namespaces).

Matt's code, which he adapted from YUI to namespace off the window object instead of the YAHOO object:

window.object_mes_namespace = function() {   
    var a = arguments,    
        o = window,   
        i = 0,   
        j = 0,   
        tok = null,   
        name = null;   

    // iterate on the arguments   
    for (i = 0; i < a.length; i = i + 1) {   
        tok = a[i].split(".");   

        // iterate on the object tokens   
        for (j = 0; j < tok.length; j = j + 1) {   
            name = tok[j];             
            o[name] = o[name] || {};   
            o = o[name];   
        }   
    }   

    return o;   
}  

Note the o[name] = o[name] || {}; line, which parallels your example.

like image 95
jball Avatar answered Sep 27 '22 00:09

jball