[b]1. 构造函数方式[/b]
Problem: 这种方式会导致每个对象都有自己的 showColor() .
[b]2. 混合的构造函数/原型方式[/b]
[b]3. 改进版:将方法封装到类定义里面:[/b]
function Car(sColor,iDoors,iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.showColor = function() {
alert(this.color);
};
}Problem: 这种方式会导致每个对象都有自己的 showColor() .
[b]2. 混合的构造函数/原型方式[/b]
function Car(sColor,iDoors,iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike","John");
}
Car.prototype.showColor = function() {
alert(this.color);
};Problem: 把方法定义在类外部[b]3. 改进版:将方法封装到类定义里面:[/b]
function Car(sColor,iDoors,iMpg) {
//Define Properties
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike","John");
//Define Methods
if (Car._initialized) return;
Car._initialized = true;
Car.prototype.showColor = function() {
prt(this.color);
};
}
本文探讨了JavaScript中构造函数的三种使用方式及其潜在问题。首先介绍了简单的构造函数方法,指出其导致每个实例都有独立的方法副本的问题。接着讨论了混合构造函数与原型的方式,这种方法虽然解决了方法共享问题但存在类方法定义于外部的不足。最后提出了一种改进方案,通过在构造函数内部初始化原型方法来优化代码结构。
3006

被折叠的 条评论
为什么被折叠?



