Loading ...
Sorry, an error occurred while loading the content.

Does a global variable exist?

Expand Messages
  • Douglas Crockford
    There is a common pattern in Ajax libraries now to keep a single object that contains the library s stuff. Since the library may be distributed over several
    Message 1 of 3 , Jul 8 11:26 AM
    • 0 Attachment
      There is a common pattern in Ajax libraries now to keep a single object that contains the library's stuff. Since the library may be distributed over several files that may load in an unexpected order, each component file may be required to initialize that object if it does not already exist.

      The simplest pattern is

      var NAMESPACE = NAMESPACE || {}:

      Some editions of IE required a slightly sloppier

      var NAMESPACE;
      NAMESPACE = NAMESPACE || {};

      A falsy check is generally good enough. If it is necessary to know for certain that a variable has not been declared, use

      hasOwnProperty(name)

      The var statement should not be used in an if statement because of hoisting.
    • Douglas Crockford
      Correction: this.hasOwnProperty(name)
      Message 2 of 3 , Jul 8 4:02 PM
      • 0 Attachment
        Correction:
        this.hasOwnProperty(name)
      • pauanyu
        ... What about: var NAMESPACE; if (typeof NAMESPACE !== object ) { NAMESPACE = {}; } True, a falsy check is generally good enough; I m talking about a
        Message 3 of 3 , Jul 8 8:01 PM
        • 0 Attachment
          --- In jslint_com@yahoogroups.com, "Douglas Crockford" <douglas@...> wrote:
          >
          > There is a common pattern in Ajax libraries now to keep a single object that contains the library's stuff. Since the library may be distributed over several files that may load in an unexpected order, each component file may be required to initialize that object if it does not already exist.
          >
          > The simplest pattern is
          >
          > var NAMESPACE = NAMESPACE || {}:
          >
          > Some editions of IE required a slightly sloppier
          >
          > var NAMESPACE;
          > NAMESPACE = NAMESPACE || {};
          >
          > A falsy check is generally good enough. If it is necessary to know for certain that a variable has not been declared, use
          >
          > hasOwnProperty(name)
          >
          > The var statement should not be used in an if statement because of hoisting.
          >

          What about:

          var NAMESPACE;
          if (typeof NAMESPACE !== "object") {
          NAMESPACE = {};
          }

          True, a falsy check is generally good enough; I'm talking about a situation where you want a more fine-grained test.
        Your message has been successfully submitted and would be delivered to recipients shortly.