Javascript中创建对象类的两种常规较好的方式

1.混合的构造函数/原型方式

function Car(sColor, iDoors, iMpg){
   this.color = sColor;
   this.doors = iDoors;
   this.mpg = iMpg;
   this.drivers = new Array("Mike", "Sue");
}

Car.prototype.showColor = function(){
   alert(this.color);
};

测试:
var oCar1 = new Car("red", 4, 23);
var oCar2 = new Car("blue", 3, 25);
oCar1.drivers.push("Langzi");

alert("oCar1.drivers:" + oCar1.color + ";oCar1.drivers:" + oCar1.drivers);
alert("oCar2.drivers:" + oCar2.color + ";oCar2.drivers:" + oCar2.drivers);

2.动态原型方法:

function Car(sColor, iDoors, iMpg){
   this.color = sColor;
   this.doors = iDoors;
   this.mpg = iMpg;
   this.drivers = new Array("Mike", "Sue");
  
   if(typeof Car._initialized == "undefined"){
    Car.prototype.showColor = function(){
     alert(this.color);
    };
   }
   Car._initialized = true;
}

测试:
var oCar1 = new Car("red", 4, 23);
var oCar2 = new Car("blue", 3, 25);
oCar1.drivers.push("Langzi");

alert("oCar1.drivers:" + oCar1.color + ";oCar1.drivers:" + oCar1.drivers);
alert("oCar2.drivers:" + oCar2.color + ";oCar2.drivers:" + oCar2.drivers);

你可能感兴趣的:(JavaScript)