The first statement defines a new object with a single property named key0.
The second statement assigns a value to the object's property named key1. Since the object doesn't have its own property named key1, the property is created.
The third statement is identical in effect to the second statement. The main reasons to use bracket notation instead of dot notation are:
properties with special characters, e.g., collection["foo-bar"] refers to a property called foo-bar, but collection.foo-bar performs a subtraction operation on collection.foo and bar.
variable property names, e.g., you can do var propName = "key0"; collection[propName] = ...
The only other way to define properties is with Object.defineProperty (and the multiple variant Object.defineProperties). This allows you to define properties that behave in special ways.
Object.defineProperty(collection, "key3", {
enumerable: false, // property will not show up in for-in loops
configurable: false, // property cannot be changed
set: function(val) {
alert("we tried to set key3 to " + val);
},
get: function() {
alert("this code runs when we get collection.key3");
return "value3";
}
});
collection.key3 = 6; // alerts "we tried to set key3 to 6"
collection.key3; // alerts "this code runs when we get collection.key3"
// and returns the string "value3"
collectioncontained with an object that contains one property. That's not the same as "adding" a property to an already existing object.Object.definePropertyandObject.defineProperties. Note thatobj.foois just syntactic sugar forobj['foo'].