Everything in JavaScript is an object, though some are more objective (haha). The easiest way to create an object is the object literal:
var x = {};
var y = {
name: "Pete",
age: 15
};
The type of an object is "object":
typeof {} // "object"
Dot Notation
You can write and read properties of an object using the dot notation:
y.name // "Pete" y.age // 15 x.name = y.name + " Pan" // "Pete Pan" x.age = y.age + 1 // 16
Array Notation
Or you write and read properties using the array notation, which allows you to dynamically choose the property:
var operations = {
increase: "++",
decrease: "--"
}
var operation = "increase";
operations[operation] // "++";
operations["multiply"] = "*"; // "*"
Iteration
Iterating over objects is easy with the for-in-loop:
var obj = {
name: "Pete",
age: 15
};
for(key in obj) {
alert("key is "+[key]+", value is "+obj[key]);
}
Note that for-in-loop can be spoiled by extending Object.prototype (see Object.prototype is verboten) so take care when using other libraries.
jQuery provides a generic each-function to iterate over properties of objects, as well as elements of arrays:
jQuery.each(obj, function(key, value) {
console.log("key", key, "value", value);
});
The drawback is that the callback is called in the context of each value, therefore you lose the context of your own object if applicable. More on this below at Functions.
Boolean default
An object, no matter if it has properties or not, never defaults to false:
!{} // false
Prototype
All objects have a prototype property. Whenever the interpreter looks for a property, it also checks the prototype. jQuery uses that extensively to add methods to jQuery instances.
var form = $("#myform");
form.clearForm; // undefined
form.fn.clearForm = function() {
return this.find(":input").each(function() {
this.value = "";
}).end();
};
form.clearForm() // works for all instances of jQuery objects, because the new method was added to the prototype
(This example needs clarification: how does it modify the prototype when the word "prototype" doesn't appear anywhere? The implication is that form.fn is simply an alias for form.prototype, but if that's the case then it should be explained. :-?)
In javascript:the definitive guide 5 edition,dont add attibute to Object.prototype

