JavaScript的三种构造模式

在创建一个对象的时候,js有三种可以选择的方法

1. Factory Pattern

function createCourse(number, room, teacher){
	var course = new Object();
	course.number = number;
	course.room = room;
	course.teacher = teacher;
	
	course.toString = function(){
		return 'The course '+this.number+' is taken in room '+this.room+' by teacher '+this.teacher;
	};
	course.showCourse = function(){
		document.write(this);
	};
	return course;
}

var c1 = createCourse(1, 'R110', 'Mike');
c1.showCourse();

2. Constructor Pattern

function Course(number, room, teacher){
	this.number = number;
	this.room = room;
	this.teacher = teacher;
	
	this.toString = function(){
		return 'The course '+number+' is taken in room '+room+' by teacher '+teacher;
	};
	this.showCourse = function(){
		document.write(this);
	};
};

var  c2 = new Course(2,'T101', 'Matti');
c2.showCourse();

3. Prototype Pattern

function Course2(){
}
Course2.prototype.number = 'No course number';
Course2.prototype.room = 'No room number';
Course2.prototype.teacher = 'No teacher';

Course2.prototype.toString = function(){
	return 'The course '+this.number+' is taken in room '+this.room+' by teacher '+this.teacher;
};
Course2.prototype.showCourse = function(){
	document.write(this);
};

var c3 = new Course2();
c3.showCourse();

Prototype Pattern在内存和资源的利用上要更有效些,prototype pattern可以给对象设置默认值和默认方法

“Another alternative is the Prototype Pattern. With this pattern, memory and resources are used more effeciently as multiple objects share resources. The Constructor fuction boyd is (typically) null. Prototypies and functions are assigned to the constructed object's prototype. Prototype is a default property within and object that contains properties and methods available to all instances of that object. This technique allows defining 'default values' for objects and object functions. The object creation and call does not specify property values." -- 《Advanced Topics in Web Development - Fall 2011》

相关推荐