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》

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值