Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to create a Namespace/Class type structure in JavaScript [closed]

I am trying to settle on a method that will provide me the most elegant way of wrapping my code in Namespace/Unit like objects. For example Google Maps API's var a = Google.Maps.Foo();, which I think seems quite clean.

I'd like it to enclose (if that is the right term) the jQuery No Conflict $ sign as well.

So far I am liking:

// Top level container for sub objects
var myApp = myApp || {}; 

// An object to be held in myApp     
(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 );

        return "Fried!";
    };

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

}( window.myApp.skillet = window.myApp.skillet || {}, jQuery ));

Can anyone expand on this, point out potential problems, or just offer a better methodology in general?

like image 923
Gga Avatar asked Mar 27 '13 12:03

Gga


People also ask

What is a namespace object in JavaScript?

Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

What is the global namespace in JavaScript?

The global namespace is the top space of Javascript that contains the variables. In a browser, it's known as the window.

Is namespace a class?

The namespace and classes are two different concepts. Classes are datatypes. Classes are basically extended version of structures. Classes can contain data members and functions as members, but namespaces can contain variables and functions by grouping them into one.


1 Answers

Check this JavaScript Module Pattern and this Learning JavaScript Design Patterns

Module example:

var MyModule = (function($){
  var MY_CONSTANT = 123;

  var _myPrivateVariable = 'TEST MEH';
  var _$myPrivateJqueryObject = $('div.content');

  var _myPrivateMethod = function(){
    alert('I am private!');
  };

  var myPublicMethod = function(){
    console.log('Public much?');
  }

  return {
      myPublicMethod : myPublicMethod 
  };

})(jQuery);

MyModule.myPublicMethod();

Class example:

function Person(name, age){
   this.name = name || '';
   this.age = age || -1;
}

Person.prototype.greet= function(){
   console.log('Hi! My name is' + this.name + '. Old ' + this.age + ' I am.');
}

var person = new Person("John", 12);
person.greet();
like image 100
kayz1 Avatar answered Oct 11 '22 14:10

kayz1