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
- What is Object Oriented JavaScript?
- The Benefits of OO JavaScript
- JavaScript's Built in Objects
- Extending Built In Objects
- Creating Objects from Existing Objects
- Creating New Objects Without Copying Existing Ones
- Dot Notation and "this"
- prototype
- Inheritance and "constructor"
- Associative Array Notation
- Create Method if Doesn't Exist
- "self" and Multiple Objects
- Defining Objects with JSON
- Namespaces
- Lazy Definition
- Extending Methods
- Copying Objects
- Private Properties and Privileged Methods
- Public Access to Private Methods
- Chaining Methods
- Singletons

