[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);
};
}