js创建对象的5种方式

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			//直接创建式
			// var student = new Object();
			// student.name="小黑糖";
			// student.age=23;
			// student.dohomework = function(){
			// 	console.log(this.name+"正在写作业");
			// }
			// student.dohomework();
			
			//初始化式
			// var student ={
			// 	"name":"Tom",
			// 	mobile:"123456",
			// 	doHomework:function(){
			// 		console.log(this.name+"正在写作业..."+this.mobile);
			// 	}
			// }
			// student.doHomework();
			
			//构造方法式
			// function Student(name,age){
			// 	this.name =name;
			// 	this.age=age;
			// 	this.sleeping=function(){
			// 		console.log(this.name+"正在睡觉")
			// 	}
			// }
			// var student = new Student("hh","15");
			// student.sleeping();
			
			//原型式
		  // function Student(){}
		  // Student.prototype.name="ll";
		  // Student.prototype.age="14";
		  // Student.prototype.doHomework=function(){
			 //  console.log(this.name+"正在做作业");
		  // }
		  // var student = new Student();
		  // student.doHomework();
		  
		  // student =new Student();
		  // student.name="qaz";
		  // student.doHomework();
		  
		  
		  //混合式(构造方法式+原型式)
		  
		  function Student(name,age){
			  this.name=name;
			  this.age=age;
		  }
		  Student.prototype.doHomework = function(){
			  console.log(this.name+"正在写作业");
		  }
		  
		  var student = new Student("lily","12");
		  student.doHomework();
		</script>
	</body>
</html>

posted @ 2021-06-04 15:13  imetal  阅读(89)  评论(0)    收藏  举报