O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.4. Objects as Bags of Properties, Duck Typing, and JSON

In JavaScript, objects are really no more than bags of properties. There is no real concept of class and no type checking. This fact leads to code that has a contract around the properties that an object has rather than the type that it is. This is sometime called duck typing from the idea that if it looks like a duck and quacks like a duck, then for all intents and purposes it can be considered is a duck. This also means that we could create a Point object as:

var point = new Object();
point.x = 0;
point.y = 0;

JavaScript, however, has a shortcut notation for this kind of thing, called JavaScript Object Notation (JSON). JSON lets us write this as:

var point = {x:0,y:0};

JSON allows objects to be nested to an arbitrary level. It may contain all valid JavaScript objects, making it ideal for defining configuration.:

var config = {
                     param1: 0.0,
                     functionToRun: function() { ...},
                     args: [0.0,'x',{x:0,y:0}]
             };

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required