1. Home
  2. Computing & Technology
  3. JavaScript

Object Oriented JavaScript
13. Defining Objects with JSON

By , About.com Guide

JavaScript Object Notation (JSON) is a convenient short way to define objects in JavaScript.

The first thing that JSON allows us to abbreviate is the basic statement that creates the new object in the first place. Where we might have specified.


var myObject = new Object();

With JSON we can replace that with:


var myObject = {};

While this saving isn't all that great when we look just at that single piece of code the JSON way becomes a significantly shorter way of writing the code when we want to assign values to a while lot of properties at the same time. So foe example instead of:


function myObject(arg1, arg2) {
this.p1 = arg1;
this.p2 = arg2;
}
var myNewObj1 = new myObject(parm1, parm2);

With JSON we end up with:


var myNewObj1 = {'p1': parm1, 'p2': parm2};

All that you need to do to convert any object constructor into JSON is to use the {} notation to create the new object and then define the properties of the new object using property name : property value inside the {}. This becomes particularly convenient when our object has lots of properties to set up.

While it is possible to also use this notation to define methods as well as properties, the amount of code that you save in defining methods that way is insignificant compared to the saving you get when defining properties. Also using JSON to define your methods also has the disadvantage of creating a separate copy of the method for each object - something that is best resolved by using the prototype way of creating methods that we looked at earlier.

All the Object Oriented JavaScript Tutorials

  1. What is Object Oriented JavaScript?
  2. The Benefits of OO JavaScript
  3. JavaScript's Built in Objects
  4. Extending Built In Objects
  5. Creating Objects from Existing Objects
  6. Creating New Objects Without Copying Existing Ones
  7. Dot Notation and "this"
  8. prototype
  9. Inheritance and "constructor"
  10. Associative Array Notation
  11. Create Method if Doesn't Exist
  12. "self" and Multiple Objects
  13. Defining Objects with JSON
  14. Namespaces
  15. Lazy Definition
  16. Extending Methods
  17. Copying Objects
  18. Private Properties and Privileged Methods
  19. Public Access to Private Methods
  20. Chaining Methods
  21. Singletons
Explore JavaScript
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Object Oriented JavaScript
  6. Defining Objects with JSON>

©2010 About.com, a part of The New York Times Company.

All rights reserved.