Objects
All objects in Javascript is class-free objects.
Javascript include two main types, One is simple types, e.g. number(NaN, Infinity), string, boolean(true, false), null and undefined, number, string and boolean can own their methods. The other one is objects, e.g. array, function, regular expresion and object, they are all keyed collections.
The following values will be treated as false:
false, null, undefined, empty string (“”), 0, NaN
All other values will be treated as true.
- Object Literals
Object is the container of properties. The property key could include empty string (“”) and the property value could include everything except the undefined.
var obj = { “Name”: “Johnson”, City: { }, “”: 23 };
If the property key name is a qualified identifier, the quotation surrounding it can be ignored.
There is another way to create an object:
var obj = new Object();
The statement above is equal to:
var obj = {};
Object.call(obj, args…); // obj will be addressable by the key word this in the Object function
- Retrieval
There are two way to fetch the property value.
obj[""];
obj.City;
If the property key is a qualified identifier, we prefer to use the dot (.) way. If you try to query a non-existent property, it will return undefined.
obj.nonexistent == underfined;
The || operator could be used for assigning default value:
var name = obj.nonexistent || “(none)”;
The && operator could be used for avoiding exception occurring:
var name = obj.Name && obj.Name.length;
- Reference
Objects are reference assignment. So
var a = b = c = {};
is different from
var a = {}, b = {}, c = {};
The first one above are all referring to the same object.
- Reflection
Use typeof to get the type:
typeof “” // ‘string’
typeof (123) // ‘number’
typeof null // ‘object’
typeof true // ‘boolean’
// other possible result: ‘underfined’, ‘function’
Use hasOwnProperty to determine if the current object own the property:
obj.hasOwnProperty(‘constructor’) // false
- Prototype
Every object is linked to a prototype and can inherit properties for its prototypes. All objects created by literal ({}) will be linked to Object.prototype.
When a property is queried, its prototype or prototype’s prototype may be search until to Object.prototype. Not found will answer undefined.
We can add properties to object’s prototype:
obj.prototype.add = function(a, b) { return a + b; }
All objects link to this prototype will support this property immediately, both created objects and will be created objects.
- Enumeration
for in expression enumerate all object’s properties and its prototype’s properties, in a random sequence.
var name;
for (name in obj) { alert ( obj[name] ); };
- Delete
Object’s properties could be deleted.
delete obj.name; // typeof (obj.name) == undefined