JSON syntax for javascript oldies/newbies

If you have started using javascript after a big gap and have come across strange syntax comprising of curly braces, colons and commas, you may find this post useful. Those who have been in constant touch with Javascript, you know for sure, I am talking about JSON. I have observed this that many are unaware of JSON syntax of writing javascript. JSON is not discussed in older javascript books and literature.

Now for those interested, let me tell them what it means:

function Person()
{this.Name = "Ashish";}
var x = new Person();
alert(x.Name);

The classic javascript syntax. This uses the ‘function’ construct to create ‘Person’ objects. This is form of OOP with javascript. More details regarding OOP in javascript (and how it differs from class based OOP languages like C++,Java) is given here:
http://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

var y = { 'FirstName' : 'ABC','LastName': 'XYZ'};
alert(y.Name);

Now the same code can be written as above. The above is JSON syntax of declaring javascript objects. JSON is special way of writing javascript to create objects.

Here is another example:

function Person()
{
this.FirstName = "";
this.LastName = "";
this.GetFullName = function()
{ return this.FirstName + " , " + this.LastName;}
}

Same, can be written in JSON syntax like this:

Person = function()
{
return {
FirstName : '',
LastName : '',
GetFullName : function ()
{ return this.FirstName + " , " + this.LastName;}}
}

This kind of syntax, does not necessarily have any big advantage when it comes to object creation. However it is being widely adopted in modern javascript libraries.




Copyright (c) 2007-2017 Ashish Patil . Please read FAQ for more details.

comments powered by Disqus