JavaScript Code Organization | The Object Literal

Generation Next JavaScript Code Structure

JavaScript Code Structure When you are adding simple functionality to your website with javascript or jQuery at client side, you need to plan, how to organize code. I'll take a look at various code organization design and patterns you can use in your javascript or jQuery application.

Generation Next JavaScript Code Structure Part - 1


Encapsulate: The first step to code organization is separating pieces of your application into small chunks.

The Object Literal
The simplest way to encapsulate related code. It does not support any privacy (like public and private) for properties and methods, but it is useful for get rid off anonymous functions from your code, centralizing configuration options.

<!doctype html> <html lang="en"> <head> <script src="jquery.js"></script> </head> <body> <div class="dvResult"> Result: </div> <script> 'use strict' // An object literal var yourVariable = { // Public variables and functions     yourProperty: "Hello World",     yourMethod: function() {         $('.dvResult').append(yourVariable.yourProperty);     },     init: function(settings) {         yourVariable.settings = settings;     },     readSettings: function() {         $('.dvResult').append( yourVariable.settings );     } }; yourVariable.yourMethod(); yourVariable.init(' by SW Class.'); yourVariable.readSettings(); </script> </body> </html>

Web Browser Response

Result: Hello World by SW Class.

Here an object assigned to a variable. The object has one property and many methods. All of the properties and methods have public access.

5 Minutes for JavaScript best practices

Hope this 5 minute time spent here in this article, will change your mind set to code javascript in different way...

Note: The Object Literal have limitations that is public properties and methods. In next section i will explain how to overcome these limitations by using the Module Pattern which offers privacy for variables and functions as well as exposing a public properties and methods if desired.

Click here to know more about the Module Pattern

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories