Javascript OOP object literal


Everything in Javascript is object. Arrays, functions objects, regular expression are all objects. They are all passed by reference!

Object in Javascript looks like HashMap in Java

Object Literal:

var person = {
	name : "Peter",
	age : 18,
	email : "[email protected]",
	address : {
		street : "Peter's street",
		city : "Peter's city"
	}
};

Retrieval

object can be retrieve by . operator or [] operator. usually . is preferred because it is more readable. If the property is not defined, undefined will be return.

Attempting to retrieve values from undefined will throw a TypeError exception

If a property is not found, then javascript will look for the property in the prototype, if the property is still not found, javascript will look at its prototype until Object.protptype. If still can't find it, undefined will be return.


for... in

for... in loop can be used to inspect objects in Javascript.


var person = {
		name: "Pete",age: 25,email: "x@y",date: new Date(),
		complex: {
			key1: 'val1',
			key2: 'val2'
		},
		sayHi: function(){console.log("HI");}
};
person.sayHi();

//show person without function
for( var p in person ){
	if( typeof  person[p] !== 'function' )
		console.log( p + " : " + person[p] );
}

output:

HI
name : Pete
age : 25
email : x@y
date : Sat Aug 11 2012 13:53:25 GMT-0400 (Eastern Daylight Time)
complex : [object Object]


delete

delete a property from an object

var person = {
	name : "Pete",
	age : 25,
	email : "x@y",
};
delete person.age;

// show person without function
for ( var p in person) {
	console.log(p + " : " + person[p]);
}

output:

name : Pete
email : x@y





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章