Creating objects
var emptyObject = {};
var objectWithProperties={
property1: "value1",
property2: "value2",
property3: "value3"
};
var complexObject = {
stringProperty: "stringValue",
numberProperty: 1,
methodProperty: function(argument){
return argument + 5;
}
};
var outsideObject = {
nestedObject:{
ultraNestedObject: "value"
}
};
Accessing properties in objects
return objectWithProperties.property1;
//=>"value1"
return objectWithProperties["property1"];
//=>"value1"
return objectWithProperties["prop" + "erty1"];
//=>"value1"
return outsideObject["nestedObject"]["ultraNestedObject"];
//=>"value"
return outsideObject.nestedObject;
//=>ultraNestedObject: "value"
complexObject.methodProperty(2);
//=>7
Adding and deleting properties in objects
console.log(emptyObject);
//{}
emptyObject.property1 = "I'm new!";
emptyObject["property2"] = "Me too!";
emptyObject.method = function(){
return "I'm a function in an object, so I'm a new method.";
}
console.log(emptyObject);
//{property1: "I'm new!",
property2: "Me too!",
method: function(){
return "I'm a new function in an object, so I'm a new method."
}
}
delete emptyObject.method();
console.log(emptyObject);
//{property1: "I'm new!",
property2: "Me too!"
}