四种Javascript创建对象示例

本文详细探讨了JavaScript中创建对象的四种常见方法:字面量语法、构造函数、原型对象和对象字面量。通过实例解析,深入理解各自的特点和应用场景,帮助提升JavaScript编程能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
	<head>
		<title>Just Test</title>
		<script language="javascript">
			//JSON 格式
			var o = {
				name : "zhouqinsheng",
				age : 26,
				school : "anhui",
				score : {
					english : 31,
					math : 0
				}
			};

			//Object 格式
			var o1 = new Object();
			o1.name = "heze";
			o1.age = 46;
			o1.school = "hunan",
			o1.score = new Object();
			o1.score.english = 65;
			o1.score.math = 1;
			
			//匿名构造器格式 
			var o2 = new function() {
				this.name = "heze";
				this.age = 46;
				this.school = "hunan",
				this.score = new function () {
					this.english = 65;
					this.math = 2;
				};
			};

			//命名构造器格式
			function ClassO() {
				this.name = "heze";
				this.age = 46;
				this.school = "hunan";
				
				function Score() {
					this.english = 65;
					this.math = 3;
				};
				this.score = new Score();
			};

			var o3 = new ClassO();

			//基于prototype的命名构造器格式
			function ClassOX() {				
			};
			ClassOX.prototype.name = "heze";
			ClassOX.prototype.age = 46;
			ClassOX.prototype.school = "hunan";
				
			function ScoreX() {				
			};
			ScoreX.prototype.english = 65;
			ScoreX.prototype.math = 4;
			ClassOX.prototype.score = new ScoreX();

			var o4 = new ClassOX();

			function show(e) {
				alert("name=" + e["name"]
					+ "\nage=" + e['age']
					+ "\nschool=" + e.school
					+ "\nenglish=" + e.score.english
					+ "\nmath=" + e.score.math);
			};
		</script>
	</head>
	<body onload="show(o);show(o1);show(o2);show(o3);show(o4)">
	</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值