javascript tutorial - [Solved-5 Solutions] Declare a namespace in JavaScript - javascript - java script - javascript array



Problem:

How do I declare a namespace in JavaScript?

Solution 1:

if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}
click below button to copy the code. By JavaScript tutorial team

Solution 2:

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();
click below button to copy the code. By JavaScript tutorial team

Solution 3:

(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 ));

//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 ));
click below button to copy the code. By JavaScript tutorial team

Solution 4:

var ns = new function() {

    var internalFunction = function() {

    };

    this.publicFunction = function() {

    };
};
click below button to copy the code. By JavaScript tutorial team

Solution 5:

For example:

var your_namespace = your_namespace || {};

var your_namespace = your_namespace || {};
your_namespace.Foo = {toAlert:'test'};
your_namespace.Bar = function(arg) 
{
    alert(arg);
};
with(your_namespace)
{
   Bar(Foo.toAlert);
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Declare a namespace in JavaScript