JavaScript-自定义对象

一、直接创建对象

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			//直接创建对象
			var person = new Object();
			person.name = "Lucy";
			person.study=function(){
				console.log(this.name + "正在学习")
			}
			person.study();
		</script>
	</body>
</html>

在这里插入图片描述

二、初始化器方式

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			//初始化器方式
			var student={
				name:"Tom",
				doHomework:function(){
					console.log(this.name + "正在做作业")
				},
				study:function(age) {
					console.log(this.name +"年龄" + age + "正在研究");
				}
			}
			student.doHomework();
			student.study("123");
		</script>
	</body>
</html>

在这里插入图片描述

三、构造方法式

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			//构造方法式
			function Man(name){
				this.name = name;
				this.study = function(){
					console.log(this.name + "在学习");
				}
			}
			var man = new Man("Timmy");
			man.study();
		</script>
	</body>
</html>

在这里插入图片描述

四、原型式

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			//原型式
			function Woman() {}
			Woman.prototype.name="Jim";
			Woman.prototype.study=function() {
				console.log(this.name + "正在努力学习");
			}
			var woman = new Woman();
			woman.study();
		</script>
	</body>
</html>

五、混合式

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			//混合式
			function People(name) {
				this.name=name;
			}
			People.prototype.study = function(){
				console.log(this.name + "正在研究");
			}
			var people = new People("张三");
			people.study();
		</script>
	</body>
</html>

在这里插入图片描述
注意:其中常用的创建对象的方法为直接创建对象和混合式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值