Blog

Filter posts by Category Or Tag of the Blog section!

Object Literals and benefits in java scripts

Saturday, 01 March 2014

JavaScript, by default does not come with built-in namespace or class but as it's extremely a flexible language you can create namespace in JavaScript by object literals. Based on wikipedia definition "literal is a notation for representing a fixed value in source code."  you can simply create Object literal by using: 

  1. A colon which separates the property name from value.
  2. A comma which separates each name and value pair from the next.

 

For example:

var myInfo = {
    Name: "Ehsan",
    Age: 25,
    Job: "Developer"
};

 

You can also define the nested object literal like this:

 

var myInfo = {

Info1:{
    Name: "Ehsan",
    Age: 25,
    Job: "Developer" 
    }, 
Info2:{
    Website:"ehsanghanbari.com",
    Mail:"mails@ehsanghanbari.com"
    }
};

 

Object literals make for good code organization, means of encapsulating data, enclosing it in a tidy package to minimize the use of global variables which can cause problems when combining code. Imagine if you wanted to write all of the code above in your functions, it would be something like stars war!

By using object literal there is no need to invoke constructors directly or maintain the correct order of arguments passed to functions and unobtrusive event handling.

Rather than static values, object literal could contain kinds of value, such as attribute, array or function:

 

Var obj={
        Title: "a good title",
        Books: ["JavaScript", "Domain Driven Design"],
        order:  function() {console.log("blah blah");
           }
}

 

In comparison to the constructor, constructors need to be executed so it will be slower. But object literals need to be parsed (defined) in loading the script.

Note: When you define an object as literal, you build the object by code; so if you use this keyword it will no meaning because it does not exist yet.

Category: Software

Tags: JavaScript

comments powered by Disqus