javascript 创建对象(object)

本文详细介绍了JavaScript中对象创建的多种方式,包括构造函数模式、原型模式、组合模式和动态模式,通过实例代码深入理解每种模式的特点和应用场景。

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript 创建对象</title>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript">
	println("---对象创建方式---");
	//构造函数模式
	println("----构造函数模式-----");
	function Person(name,color){
		this.name = name;
		this.color = color;
		this.sayName = function(){
			println("name = " + this.name);
		}
	}
	
	var p = new Person("zizhu", "red");
	p.sayName();
	
	//原型模式
	println("----原型模式-----");
	function Dog(){}
	Dog.prototype.name = "zizhu8";
	Dog.prototype.color = "black";
	Dog.prototype.showInfo = function(){
		println("name = " + this.name + ", color = " + this.color);
	}
	
	var dog = new Dog();
	dog.showInfo();
	
	//组合模式
	println("----组合模式-----");
	function Pig(name,color){
		this.name = name;
		this.color = color;
	}
	Pig.prototype.showInfo = function(){
		println("name = " + this.name + ", color = " + this.color);
	}
	
	var pig = new Pig("pig", "blue");
	pig.showInfo();
	
	//动态模式
	println("---动态模式---");
	function Cow(name,color){
		this.name = name;
		this.color = color;
		if(typeof this.showInfo != "function"){
			alert("first alert!!!");
			Cow.prototype.showInfo = function(){
				println("name = " + this.name + ", color = " + this.color);
			}
		}
	}	
	
	var cow = new Cow("cow", "black");
	cow.showInfo();
	var cow1 = new Cow("cow1", "black1");
	cow1.showInfo();	
	
</script>
</head>
<body>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值