functionObjectName(yName,yAge) { this.name = yName; this.age = yAge; } //调用时: var myObject = new ObjectName("kk",80); // ObjectName 里面的函数会被执行 document.write("name = " + myObject.name + "<br> age = " + myObject.age);
2. 使用简略语句快速创建对象
1) 类
1 2 3 4 5 6 7 8 9 10 11 12
//正常写法 var car = newObject(); car.color = "red"; car.wheels = 4; car.hubcaps = "spinning"; 简略写法: var car = { color: "red", wheels:4, hubcaps:"spinning" } //对象 car 就此创建,不过需要特别注意,结束花括号前一定不要加 ";" 否则在 IE 会遇到很大麻烦。
2) 数组
1 2 3 4
//正常数组是这样写的: var movies = newArray('Transformers','Transformers2','Avatar','Indiana Jones 4'); //更简洁的写法是: var movies = ['Transformers', 'Transformers2', 'Avatar', 'Indiana Jones 4'];
3)关联数组
这样一个特别的东西。 你会发现很多代码是这样定义对象的:
1 2 3 4 5 6
var car = newArray(); car['colour'] = 'red'; car['wheels'] = 4; car['hubcaps'] = 'spinning'; //遍历的时候 for ( var key in car ) { alert(key + " : " + car[key]); }