日期:2014-05-16  浏览次数:20416 次

[原]JavaScript学习笔记(七.创建对象)

1.工厂模式创建对象--无参构造方法

?

//	工厂方式有一个弊端,就是每个对象被实例化时,都会实例化类中的方法
//	会造成每个对象都有独立的方法版本
	function createStudentFactory()
	{
		var stu = new Object();
		stu.Id = "1";
		stu.Name = "stu";
		stu.Skill = "Ajax & javaScript";
		stu.showSkill = function()
		{
			alert(stu.Skill);	
		}
		return stu;
	}
	
	//不支持方法的重载哟!
	//function createStudentFactory(id,name,skill)
	//{
	//}
	
	var stu = createStudentFactory();
	stu.showSkill();

?

2.工厂模式2--带参构造方法

function createStudentFactory(id,name,skill)
{
	var stu = new Object();
	stu.Id = id;
	stu.Name = name;
	stu.Skill = skill;
	stu.showSkill = function()
	{
		alert(stu.Skill);
	}
	return stu;
}
	var stu2 = createStudentFactory("2","zxh","java");
	stu2.showSkill();
?

3.混合方式--属性私有,方法共有

	function Student(id,name,skill)
	{
		this.Id = id;
		this.Name = name;
		this.Skill = skill;
		this.Likes = new Array("coding","game");
	}
	
	Student.prototype.showSkill = function()
	{
		alert(this.Skill);
	}
	
	var stu1 = new Student(1,"zxh","Ajax");
	var stu2 = new Student(2,"zxh2","Java");
	stu2.Likes.push("travel");
	
	stu1.showSkill();
	stu2.showSkill();
	alert(stu1.Likes);
	alert(stu2.Likes);	
?

?