JavaScript Object Literal Namespacing

JavaScript Object Literal is a comma separated list of name-value pairs enclosed within a curly braces, means of encapsulating lots of data under a namespace, where the name is a valid variable name and the name can be used as variable. Values can be of any data type, including array literal and object literal.

Purposes of JavaScript Object Literal notion:

  • It provides encapsulation
  • Avoiding global namespace pollution
  • Relatively straightforward to implement

A namespace is a context for identifiers, simply a namespace is an abstract container for items such as names, objects etc. Also within a namespace, the components can not share the same name.

Encapsulation, In his influential book on object-oriented design, Grady Booch defined encapsulation as “the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation.”

An example given as:

/*
* BlogPost : creating BlogPost object using object literal notation
* basic structure: {name:value, name:value};
* or can be as { name:value, { name:function(){...},...}, name:value ... }
*/
var BlogPost = {

 title: 'Welcome to My Blog',  // Blog title
 numberOfView: 0,    // Number of Blog view
 blogContent: '',    // Blog post content
 URL: 'http://mahtonu.wordpress.com', // Blog post URL
 flag: false,        // Use some flag
 lastView: null,     // Timestamp of the last Blog view

 //set blog content here
 setContent: function(content) {
 this.blogContent = content;
 },
 //get blog content
 getContent: function() {
 return this.blogContent;
 },
 //count the number of blog post view
 incrementView: function() {
 this.numberOfView++;
 },
 //set timestamp of the last Blog view
 setTimeStamp: function(time) {
 this.lastView = time;
 },
 //get timestamp of the last Blog view
 getTimeStamp: function() {
 return this.lastView;
 },
 //get blog url
 getBlogUrl: function() {
 return this.URL;
 }
};

In the avobe example the  "BlogPost" object created using object literal notion with some properties. Thus the property values can be manipulated using methods sharing the namespace. Further adding property or methods are simple enough.

More usage:

//set some post here
BlogPost.setContent('I am a body of a blog post!');
BlogPost.setTimeStamp('14th April 2010 09.00PM');
//publish your blog post
document.write('Title: '+BlogPost.title);
document.write('Post: '+BlogPost.getContent());
document.write('Link: '+BlogPost.getBlogUrl());
document.write('Posted at: '+BlogPost.getTimeStamp());
document.write('Total Viewed: '+BlogPost.numberOfView);
//got a hit increment your view no
BlogPost.incrementView();

So we are accessing and working around the properties of an object forming a namespace.

References /Further Readings:

Wiki page for Information hiding [Encapsulation Part]

Tim McCormack on Javascript object literal namespacing

Jonathan Snook on Objectifying JavaScript

Good JavaScript Study Resources

:)

Rules, Naming , Conventions

Google JavaScript Style Guide

JavaScript: The World’s Most Misunderstood Programming Language by Douglas Crockford (2001)

http://javascript.crockford.com/javascript.html

“Private Members in JavaScript” by Douglas Crockford (2001)

http://www.crockford.com/javascript/private.html

Code Conventions for the JavaScript Programming Language

http://javascript.crockford.com/code.html

ECMA-262-3 in detail

http://dmitrysoshnikov.com/

OOP: The general theory.

http://dmitrysoshnikov.com/ecmascript/chapter-7-1-oop-general-theory/

Object Oriented Programming in JavaScript

http://mckoss.com/jscript/object.htm

.

Self executing functions in JavaScript

JavaScript has bunch of cool features; one of them can be self executing functions. :)

Also this self invocation feature could be surrounded by the best practices for JavaScript.

Let’s have an example of an anonymous self invoking function:

 (function(){
 var test =  2;
 alert(test);
 })();
 

Here, test variable has its own local scope, means it doesn't interface with or pollute global scope and it dies out(remains as long as there’s somewhere in the page or in an event that references the variable you declared in your closure: Thanks Dan Beam for this correction :) ) when the function terminates.

One simple example:

 var testVar = "Hi there";

(function testFunction(str)
{
alert(str);
})( testVar );

One more scoping example(by Dan Beam):

var class = (function () {
var private = function () { alert("Hey, I'm still here!"); };
return ({ test: function () { private(); }});
})();

// more JavaScript

class.test();

Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.

I am a great fan :) of it because:

  • It keeps code to a minimum
  • It enforces separation of behavior from presentation
  • It provides a closure which prevents naming conflicts

Enormously – (Why you should say its good?)

  • It’s about defining and executing a function all at once.
  • You could have that self-executing function return a value and pass the function as a param to another function.
  • It's also good for block scoping.
  • Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)

jQuery pursue such struct.

 (function($) {
 // $() is available here
 })(jQuery);
 

It’s precisely the reason that jQuery doesn’t pollute the global namespace nearly as much as other libraries.

Cheers!

:D