JavaScript 对象

4次阅读

<html>
<head>
<script>
// 参考:http://www.w3school.com.cn/js/js_objects.asp
//JavaScript 中的所有事物都是对象:字符串、数值、数组、函数... 此外,JavaScript 允许自定义对象。funload = function(){//fun1()
// 注意, 方法 fun1 实际上为 window 对象的一个属性, 只是 window 不需要声明
//window.fun1();
//fun2();
//fun3();
fun4();}
//JavaScript 提供多个内建对象,比如 String、Date、Array 等等。对象只是带有属性和方法的特殊数据类型。// 方法是能够在对象上执行的动作。fun1 = function(){
	var message="abcd";
	alert(message.length);
	alert(message.toUpperCase());
}
// 定义并创建对象的实例
fun2 = function(){var person = new Object();
	person.name= " 胖子小胖子 ";
	alert(person.name);
	//json 方式声明对象
	var person2 = {name:" 火星人 "};
	alert(person2.name);
	for(var temp in person2){// 对象属性可视为数组
		alert(person2[temp]);
	}

}
// 使用函数来定义对象,然后创建新的对象实例
fun3 = function(){
	//this 的使用
	var temp = new function(){this.name="123456ACGDE";}
	alert(temp.name);
}
// 在 JavaScript 中,不会创建类,也不会通过类来创建对象(就像在其他面向对象的语言中那样)。JavaScript 基于 prototype,而不是基于类的。fun4 = function(){function funTemp(name){this.name = name;};
	var temp = new funTemp(" 胖子胖子 ");
	temp.sex = " 男 ";// 这里是设置对象 temp 的属性
	alert(temp.name+" "+ temp.sex);
	funTemp.prototype.age = 20;// 这里设置 funTemp 的 prototype
	alert(temp.name+" "+ temp.sex +" " + temp.age);
	var temp2 = new funTemp(" 胖子小胖子 ");
	alert(temp2.name+" "+ temp2.sex +" " + temp2.age);
	funTemp.enable = true;// 这里设置 funTemp 的属性
	alert(temp2.enable+" "+ temp2.sex +" " + temp2.age);
	var temp3 = new funTemp(" 胖子大胖子 ");
	alert(temp3.enable+" "+ temp3.sex +" " + temp3.age);
	// 注意 prototype
	// 创建一个空白对象(new funTemp(" 胖子胖子 "))。// 链接 funTemp.prototype 中的属性(键值对)到这个空对象中
	// 将这个对象通过 this 关键字传递到构造函数中并执行构造函数。// 将这个对象赋值给变量 zhang。}
</script>
</head>
<body onload="funload()">
</body>
</html>

正文完