Sunday, June 3, 2012

Javascript Namespace Declaration


What neat ways do you use for declaring JavaScript namespaces. I've come across this one:




if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}



Is there a more elegant or succinct way of doing this?



Just a bit of fun...


Source: Tips4all

18 comments:

  1. I like this:

    var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
    };

    ...

    yourNamespace.foo();

    ReplyDelete
  2. Another way to do it, which I consider it to be a little bit less restrictive than the object literal form, is this:

    var ns = new function() {

    var internalFunction = function() {

    };

    this.publicFunction = function() {

    };
    };


    The above is pretty much like the module pattern and whether you like it or not, it allows you to expose all your functions as public, while avoiding the rigid structure of an object literal.

    ReplyDelete
  3. I use the approach found on the Enterprise jQuery site, here

    Here is their example showing how to declare private & public properties and functions. Everything is done as a self-executing anonymous function.

    (function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
    var oliveOil;

    addItem( "\t\n Butter \n\t" );
    addItem( oliveOil );
    console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
    if ( item !== undefined ) {
    console.log( "Adding " + $.trim(item) );
    }
    }
    }( window.skillet = window.skillet || {}, jQuery ));


    So if you want to access one of the public members you would just go skillet.fry() or skillet.ingredients

    What's really cool is that you can now extend the namespace using the exact same syntax.

    //Adding New Functionality to the Skillet
    (function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
    console.log( skillet.quantity + " " +
    skillet.ingredient + " & " +
    amountOfGrease + " of Grease" );
    console.log( isHot ? "Hot" : "Cold" );
    };
    }( window.skillet = window.skillet || {}, jQuery ));

    ReplyDelete
  4. Is there a more elegant or succinct way of doing this?


    yes it is:

    var your_namespace = your_namespace || {};


    then you can have

    var your_namespace = your_namespace || {};
    your_namespace.Foo = {toAlert:'test'};
    your_namespace.Bar = function(arg)
    {
    alert(arg);
    };
    with(your_namespace)
    {
    Bar(Foo.toAlert);
    }

    ReplyDelete
  5. This is a follow-up to user106826's link to Namespace.js. It seems the project moved to github. The new link is now:

    http://github.com/smith/namespacedotjs

    I have been using this simple js helper for my tiny project and so far it seems to be light yet versatile enough to handle namespacing and loading modules/classes. It would be great if it would allow me to import a package into a namespace of my choice, not just the global namespace... sigh, but that's besides the point.

    It allows you to declare the namespace then define objects/modules in that namespace:

    Namespace('my.awesome.package');
    my.awesome.package.WildClass = {};


    Another option is to declare the namespace and it's contents at once:

    Namespace('my.awesome.package', {
    SuperDuperClass: {
    saveTheDay: function() {
    alert('You are welcome.');
    }
    }
    });


    For more usage examples, look at the example.js file in the source: http://github.com/smith/namespacedotjs/blob/master/example/sandbox.js

    ReplyDelete
  6. I use this approach:-

    var myNamespace = {}
    myNamespace._construct = function()
    {
    var staticVariable = "This is available to all functions created here"

    function MyClass()
    {
    //Depending on the class may build all the class here
    this.publicMethod = function()
    {
    //Do stuff
    }
    }
    //Alternatively may use prototype
    MyClass.prototype.altPublicMethod = function()
    {
    //Do stuff
    }

    function privateStuff()
    {
    }

    function publicStuff()
    {
    //code that may call other public and private functions
    }

    //List of things to place publically
    this.publicStuff = publicStuff
    this.MyClass = MyClass
    }
    myNamespace._construct()

    //The following may or may not be in another file
    myNamespace.subName = {}
    myNamespace.subName._construct = function()
    {
    //build namespace
    }
    myNamespace.subName._construct()


    External code can then:-

    var myClass = new myNamespace.MyClass();
    var myOtherClass = new myNamepace.subName.SomeOtherClass();
    myNamespace.subName.publicOtherStuff(someParameter);

    ReplyDelete
  7. Because you may write different files of javascript and later combine or not combine them in an application each needs to be able to recover or construct the namespace object without damaging the work of other files...

    One file might intend to use the namespace namespace.namespace1

    namespace = window.namespace || {};
    namespace.namespace1 = namespace.namespace1 || {};

    namespace.namespace1.doSomeThing = function(){}


    Another file might want to use the namespace namespace.namespace2

    namespace = window.namespace || {};
    namespace.namespace2 = namespace.namespace2 || {};

    namespace.namespace2.doSomeThing = function(){}


    These two files can live together or apart without colliding.

    ReplyDelete
  8. I normally build it in a closure:

    var MYNS = MYNS || {};

    MYNS.subns = (function() {

    function privateMethod() {
    // Do private stuff, or build internal.
    return "Message";
    }

    return {
    someProperty: 'prop value',
    publicMethod: function() {
    return privateMethod() + " stuff";
    }
    };
    })();

    ReplyDelete
  9. or try this approach:

    http://weblogs.asp.net/mschwarz/archive/2005/08/26/423699.aspx

    ReplyDelete
  10. I created namespace which is inspired by Erlang's modules. It is a very functional approach, but that is is how I write my js these days.

    It gives a closure a global namespace and exposes a defined set functions within that closure.

    (function(){

    namespace("images", previous, next);
    // ^^ this creates or finds a root object, images, and binds the two functions to it.
    // It works even though those functions are not yet defined.

    function previous(){ ... }

    function next(){ ... }

    function find(){ ... } // a private function

    })();

    ReplyDelete
  11. http://github.com/smith/namespacedotjs

    You gotta check that out!! :D

    ReplyDelete
  12. Here's how Stoyan Stefanov does it in his JavaScript Patterns book which I to be found very good. (Also shows how he does comments that allows for auto generated API documentation, and how to add a method to a custom object's prototype):

    /**
    * My js app
    *
    * @module myapp
    */

    var MYAPP = {};

    /**
    * A maths utility
    * @namespace MYAPP
    * @class math_stuff
    */
    MYAPP.math_stuff = {

    /**
    * Sums 2 numbers
    *
    * @method sum
    * @param {Number} a First number
    * @param {Number} b Second number
    * @return {Number} Sum of the inputs
    */
    sum: function (a, b) {
    return a + b;
    },

    /**
    * Multiplies 2 numbers
    *
    * @method multi
    * @param {Number} a First number
    * @param {Number} b Second number
    * @return {Number} The inputs multiplied
    */
    multi: function (a, b) {
    return a * b;
    }
    };

    /**
    * Constructs Person objects
    * @class Person
    * @constructor
    * @namespace MYAPP
    * @param {String} First name
    * @param {String} Last name
    */
    MYAPP.Person = function (first, last) {

    /**
    * First name of the Person
    * @property first_name
    * @type String
    */
    this.first_name = first;

    /**
    * Last name of the Person
    * @property last_name
    * @type String
    */
    this.last_name = last;
    };

    /**
    * Return Person's full name
    *
    * @method getName
    * @return {String} First name + last name
    */
    MYAPP.Person.prototype.getName = function () {
    return this.first_name + ' ' + this.last_name;
    };

    ReplyDelete
  13. After porting several of my libraries to different projects, and having to constantly be changing the top level (statically named) namespace, I've switched to using this small (open source) helper function for defining namespaces.

    global_namespace.Define('startpad.base', function(ns) {
    var Other = ns.Import('startpad.other');
    ....
    });


    Description of the benefits are at my blog post. You can grab the source code here.

    One of the benefits I really like is isolation between modules with respect to load order. You can refer to an external module BEFORE it is loaded. And the object reference you get will be filled in when the code is available.

    ReplyDelete
  14. I've written another namespacing library that works a bit more like packages / units do in other languages. It allows you to create a package of Javascript code and the reference that package from other code:

    hello.js

    Package("hello", [], function() {
    function greeting() {
    alert("Hello World!");
    }
    // expose function greeting to other packages
    Export("greeting", greeting);
    });


    example.js

    Package("example", ["hello"], function(greeting) {
    // greeting is available here
    greeting(); // Alerts: "Hello World!"
    });


    Only the second file needs to be included in the page its dependencies (hello.js in this example) will automatically be loaded and the objects exported from those dependencies will be used to populate the arguments of the callback function.

    You can find the related project here:
    Packages JS

    ReplyDelete
  15. If using a Makefile you can do this.

    // prelude.hjs
    billy = new (
    function moduleWrapper () {
    const exports = this;

    // postlude.hjs
    return exports;
    })();

    // someinternalfile.js
    function bob () { console.log('hi'); }
    exports.bob = bob;

    // clientfile.js
    billy.bob();


    I prefer to use a Makefile anyway once I get to about 1000 lines because I can effectively comment out large swaths of code by removing a single line in the makefile. It makes it easy to fiddle with stuff. Also, with this technique the namespace only appears once in the prelude so it's easy to change and you don't have to keep repeating it inside the library code.

    A shell script for live development in the browser when using a makefile:

    while (true); do make; sleep 1; done


    Add this as a make task 'go' and you can 'make go' to keep your build updated as you code.

    ReplyDelete
  16. YUI has a YUI.namespace function to do this

    ReplyDelete
  17. You can declare a simple function to providing namespaces.

    function namespace(namespace) {
    var object = this, tokens = namespace.split("."), token;

    while (tokens.length > 0) {
    token = tokens.shift();

    if (typeof object[token] === "undefined") {
    object[token] = {};
    }

    object = object[token];
    }

    return object;
    }

    // Usage example
    namespace("foo.bar").baz = "I'm a value!";

    ReplyDelete
  18. If anyone find this interesting,

    var namespace = {};
    namespace.module1 = (function(){

    var self = {};
    self.initialized = false;

    self.init = function(){
    setTimeout(self.onTimeout, 1000)
    };

    self.onTimeout = function(){
    alert('onTimeout')
    self.initialized = true;
    };

    self.init(); /* if it need to auto-initialize, */
    /* you can also call 'namespace.module1.init();' from outside the module */
    return self;

    })()


    You can optionally declare a local variable same like self and assign local.onTimeout if you want it to be private.

    ReplyDelete