How to initialize a javascript object


//Initialize an empty object
var someobj = {};

//then you can do
someobj.field1=10;
someobj.field2="string";

//Or you can do to begin with
var someobj = {field1:10,field2:"string");

//You can use this an array of objects as well
var someobjArray = [
  {field1:10,field2:"string");
  {field1:10,field2:"string");
  {field1:10,field2:"string");
];

//you can have nested objects as well
var someobj = {field1:10,
   field2:"string", 
   field3:{field1:10,field2:"string"));

How can I initialize a javascript object from a string representation

Search for: How can I initialize a javascript object from a string representation

Let's take a look at the javascript ref page at mozilla

javascript extra parentheses syntax literal notation

Search for: javascript extra parentheses syntax literal notation

Leading to a discussion on JSON

use of ( ) parantheses in javascript

Search for: use of ( ) parantheses in javascript

Some explanation pointing to closures and lifetimes

(function())() implies define an annonymous function and call that function immediately.

It is not clear how this will expand the scope of variables etc.

Another good discussion, again, leading to closures...

Pretty good discussion on the topic of parens

See if some functional programming detour helps


( function () 
{     
   var s=document.createElement("script");         
   s.src="http://mydomain.com/script.js";     
   document.body.appendChild(s);  
})();

json enclosing parens parentheses

Search for: json enclosing parens parentheses

An interesting read

The gist of it is

eval accepts a sequence of Javascript statements. The Javascript parser interprets the ?{? token, occuring within a statement as the start of a block and not the start of an object literal.

When you enclose your literal into parentheses like this: ({ data_from_the_wire }) you are switching the Javascript parser into expression parsing mode. The token ?{? inside an expression means the start of an object literal declaration and not a block, and thus Javascript accepts it as an object literal.

javascript parsing statement mode expression mode

Search for: javascript parsing statement mode expression mode

An article on closures

that explain how the returned set of functions from executing a function object can continue to use variables that are denfined in that non existing function after the call.