Ehsan Ghanbari

Experience, DotNet, Solutions

Object Literals and benefits in java scripts

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:

  1. var myInfo = {
  2.     Name: "Ehsan",
  3.     Age: 25,
  4.     Job: "Developer"
  5. };
  6.  

You can also define nested object literal like this:

var myInfo = {

  1. Info1:{
  2.     Name: "Ehsan",
  3.     Age: 25,
  4.     Job: "Developer" 
  5.     }, 
  6. Info2:{
  7.     Website:"ehsanghanbari.com",
  8.     Mail:"mails@ehsanghanbari.com"
  9.     }
  10. };

Object literals makes 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:

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

 

In comparison to 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 object as literal, you build the object by code; so  if you use this keyword it will no meaning because it's not exist yet.

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus