JSON
JavaScript Object Notation (JSON,) is one of the new buzzwords popping up around the AJAX theme. JSON, simply put, is a way of declaring an object in javascript. Let’s see an example right away and note how simple it is.
var myPet = { color: 'black', leg_count: 4, communicate: function(repeatCount){
for(i=0;i<repeatCount;i++) alert('Woof!');} };
Let’s just add little bit of formatting so it looks more like how we usually find out there:
var myPet = {
color: 'black',
legCount: 4,
communicate: function(repeatCount){
for(i=0;i<repeatCount;i++)
alert('Woof!');
}
};
Here we created a reference to an object with two properties (color and legCount) and a method (communicate.) It’s not hard to figure out that the object’s properties and methods are defined as a comma delimited list. Each of the members is introduced by name, followed by a colon and then the definition. In the case of the properties it is easy, just the value of the property. The methods are created by assigning an anonymous function, which we will explain better down the line. After the object is created and assigned to the variable myPet, we can use it like this:
alert('my pet is ' + myPet.color);
alert('my pet has ' + myPet.legCount + ' legs');
//if you are a dog, bark three times:
myPet.communicate(3);
You’ll see JSON used pretty much everywhere in JS these days, as arguments to functions, as return values, as server responses (in strings,) etc.
What do you mean? A function is an object too?
This might be unusual to developers that never thought about that, but in JS a function is also an object. You can pass a function around as an argument to another function just like you can pass a string, for example. This is extensively used and very handy.
Take a look at this example. We will pass functions to another function that will use them.
var myDog = {
bark: function(){
alert('Woof!');
}
};
var myCat = {
meow: function(){
alert('I am a lazy cat. I will not meow for you.');
}
};
function annoyThePet(petFunction){
//let's see what the pet can do
petFunction();
}
//annoy the dog:
annoyThePet(myDog.bark);
//annoy the cat:
annoyThePet(myCat.meow);