www.webdeveloper.com
Results 1 to 2 of 2

Thread: JavaScript Namespacing

  1. #1
    Join Date
    Jul 2011
    Posts
    13

    JavaScript Namespacing

    Hello,

    Can anyone explain why this:

    window.myNS = myNS || {};

    causes an error?

    myNS = myNS || {};

    So does that.

    Theses do not though.

    var myNS = myNS || {};

    window.myNS = window.myNS || {};

    Thanks advance!

  2. #2
    Join Date
    Jul 2013
    Posts
    66
    The first two will fail because you are reading a variable (myNS) that has not been declared. It will work in the last example, because you are referencing a property of the global window object, which, if not present, will be undefined (opposed to not declared!). The second-last example will work because you are implicitly declaring myNS before using it in the assignment, i.e. it is equivalent to

    var myNS;
    myNS = myNS || {};

    In fact, you can prove that this is what the compiler will actually do with an experiment. The following will throw an error:

    Code:
    function foo() {
        console.log(shouldNotExist);
    }
    
    foo();
    However, this won't:

    Code:
    function foo() {
        console.log(shouldNotExist);
        var shouldNotExist = 42;
    }
    
    foo();
    Instead, it will log undefined. The only reasonable explanation is that the compiler converted it into this:

    Code:
    function foo() {
        var shouldNotExist;
        console.log(shouldNotExist);
    
        shouldNotExist = 42;
    }
    
    foo();
    Which means, that the variable is declared at the top of the function, but not initialized until after we log it, leaving it undefined. This can be quite tricky in a situation like this:

    Code:
    if(false) {
        var foobar = 42;
    }
    
    console.log(foobar);
    Even though the if statement will never be executed, the compiler will move the variable declaration to the top of the current scope and the variable will be undefined rather than undeclared.
    Last edited by Airblader; 09-01-2013 at 06:37 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles