JavaScript中创建对象的几种方式

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
	<!--创建js对象的第一种方式:使用对象字面量的方式{}   创建一个对象(最简单,好理解,推荐使用)-->
	<script>
		var Cat={};//JSON
		Cat.name="风恋绝尘、";//添加属性并赋值
		Cat.age=22;
		Cat.sayHello=function(){
			alert("hello"+Cat.name+",今年"+Cat["age"]+"岁了");//可以使用"."的方式访问属性,也可以使用HashMap的方式访问
		}
		Cat.sayHello();//调用对象的方法(函数)
	</script>
	
	<!--用function(函数)来模拟class(无参构造函数)-->
	<script>
		function Person(){
			
		}
		var personOne=new Person();//定义一个function,如果有new关键字去"实例化",那么该function可以看做是一个类
		personOne.name="梦想之舟";
		personOne.hobby="正在敲代码";
		personOne.work=function(){
			alert(personOne.name+"is"+personOne.hobby);
		}
		personOne.work();
	</script>
	
	<!---用有参数构造函数来实现,这样定义更方便,扩展性更强(推荐使用)-->
	<script>
		function Pet(name,age,hobby){
			this.name=name;//this作用域:当前对象
			this.age=age;
			this.hobby=hobby;
			this.eat=function(){
				alert("我叫"+this.name+",我今年"+this.age+"岁了,我喜欢"+this.hobby);
			}
		}
		
		var hehe=new Pet("王鹏程",22,"打篮球");//实例化创建对象
		hehe.eat();
	</script>
	
	<!--使用工厂方式来创建对象(Object关键字)-->
	<script>
		var wcDog = new Object();
		wcDog.name="旺财";
		wcDog.age=3;
		wcDog.work=function(){
			alert("我是"+wcDog.name+"汪汪汪......"+"我今年"+wcDog.age+"岁了");
		}
		wcDog.work();
	</script>
	
	<!--使用原型对象的方式 prototype关键字-->
	<script>
		function Dog(){
			
		}
		Dog.prototype.name="旺财";
		Dog.prototype.eat=function(){
			alert(this.name+"是个吃货");
		}
		var wangcai = new Dog();
		wangcai.eat();
	</script>
	
	<!--混合模式(原型和构造函数)-->
	<script>
		function Car(name,price){
			this.name=name;
			this.price=price;
		}
		Car.prototype.sell=function(){
			alert("我是"+this.name+",我现在卖"+this.price+"万元");
		}
		var camry = new Car("凯美瑞呀",22);
		camry.sell();
	</script>
	
	<!--动态原型的方式(可以看做是混合模式的一种特例)-->
	<script>
		function Car(name,price){
			this.name=name;
			this.price=price;
			if(typeof Car.sell=="undefined"){
				Car.prototype.sell=function(){
					alert("我是"+this.name+",我现在卖"+this.price+"万元");
				}
				Car.sell = true;
			}
		}
		
		var camry = new Car("凯美瑞呀",33);
		camry.sell();
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/u012110719/article/details/49095685