31

I'm trying to improve my understanding of the global namespace in javascript and I'm curious about a few things:

  1. is there a "GOD" (i.e. a parent) object that all objects (since all things except primitives are objects) to answer to and if so would that object be "window" ?

  2. why is it bad idea to have vars/functions on a global level?

  3. if it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this? example:

    function parent(){
        var x = 'some value';//this var would be considered global to all children functions but not in the true global namespace
        function child1(){
            x.someMethod()
        } 
        function child2(){
            x*something;
        }
        function child3(){
            x+=something;
            child2()
            child1()
        }
        child3()
    }
    parent()
    
Bill Keller
  • 793
  • 7
  • 22
zero
  • 2,999
  • 9
  • 42
  • 67

4 Answers4

29
  1. Is there a god (i.e. a parent) object?

    Yes. More technically, it's the global object that all these primitives are members of; it just happens that in the browser, the window object is the global object.

    > window.String === String;
    true
    
  2. Why is it bad idea to have vars/functions on a global level?

    Because if you're adding lots of 3rd party libraries/ scripts, they all share the same global object, there's the chance of name collisions. This is a real life problem with all the libraries which use $ as an alias (jQuery, Prototype and more).

  3. If it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this?

    x shouldn't be considered global. It's part of the closure formed by declaring the child functions inside the parent() function. The problem part of your snippet is that parent() is global; what happens if some other code re-declared parent()? This would be better:

    (function () {
    
    function parent(){
        var x = 'some value';
        function child1(){
            x.someMethod()
        } 
        function child2(){
            x*something;
        }
        function child3(){
            x+=something;
            child2()
            child1()
        }
        child3()
    }
    parent()
    
    }());
    

    The fact x is accessible within the child functions isn't bad; you should have written those functions yourself, so you should be aware of the existence of x. Bear in mind that if you re-declare x within those child functions with var, you won't affect the x in parent().

Matt
  • 74,352
  • 26
  • 153
  • 180
  • for x i ment that it is global to the children functions but not to the global object meaning that all the child functions could access it without it being past as an argument – zero Mar 19 '12 at 16:44
  • @codewombat: but you'd normally only declare a function within another function **because** you needed it to access the variables in that scope. – Matt Mar 19 '12 at 16:47
  • since you have a self executing parent function if any of the code does dom manipulation should this be called at the bottom of the body node? – zero Mar 19 '12 at 16:48
  • So how would I call child3 from eg a button click? – JoshOrndorff Dec 11 '17 at 04:42
5
  1. Yes, in a browser environment the "god object" is window. It's typically called the global object, not god object though ;) In non-browser environments such as nodejs, the global object may use some other name than window.

  2. If you put everything as globals, you risk running into colliding names. There is also the matter of encapsulation - in other words, by putting variables into only the scope where it's needed, your code is usually better off.

  3. Yep, this is pretty much the preferred approach. You can also use IIFE's

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86
  • wouldn't an IIFE cause an error if within it there is code that is modifying the dom or is it better to call your js at the bottom of the body node(so to make sure all html has loaded)? – zero Mar 19 '12 at 16:41
  • the name global object is nice, but "god object" sounds so cool :D – zero Mar 19 '12 at 21:10
  • 2
    Yes the IIFE _could_ cause an error if the code within it was trying to access the DOM before it was ready. Either by placing the IIFE at the bottom of the page or by using jQuery's `$( document ).ready(function(){ ... });` – skube Feb 21 '14 at 19:43
3

If you NEED to put variables in the global namespace, and you likely will at some point, create a single object variable and add your other variables to it as properties or methods. Give the object a name that is not likely to be used by anyone else (admittedly, this is where collision problems arise, but that can be mitigated by careful, standardized naming).

e.g. Instead of:

var thing1 = 'table';
var anotherthing = 'chair';
var mypet = 'dog';
var count = 4;
var show_something: function( _txt ) { return _txt.trim(); };

Do this:

var cmjaimet_obj = {
  thing1: 'table',
  anotherthing: 'chair',
  mypet: 'dog',
  count: 4,
  show_something: function( _txt ) { return _txt.trim(); }
};

Then later call them as properties:

e.g. Instead of:

count += 2;
anotherthing = 'sofa';
console.log( show_something( 'Thing: ' + anotherthing ) );

Do this:

cmjaimet_obj.count += 2;
cmjaimet_obj.anotherthing = 'sofa';
console.log( cmjaimet_obj.show_something( 'Thing: ' + cmjaimet_obj.anotherthing ) );
Juniper Jones
  • 779
  • 6
  • 10
3
  1. As far as I know, I'd say yes, window is the parent object. However, inside an Iframe you have your own window object, distinct from surrounding window which you can access through window.parent

  2. It's a bad idea to have a LOT of global var because of potential name collision and therefore hard to detect bugs. In general it's safer to design some namespace (see the $ from jQuery, etc) and modularize code.

  3. Be careful, parent is a potential existing field of window. This taken appart, function are object so the same observation than in 2) apply here.

Matt
  • 74,352
  • 26
  • 153
  • 180
Nicocube
  • 2,962
  • 2
  • 20
  • 28
  • so is there a way to "error proof" the parent function since it's the only global object? – zero Mar 19 '12 at 16:43
  • 1
    module pattern for example: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth – Nicocube Mar 19 '12 at 16:49