JavaScript 类,对象

1. 构造函数方式
function Car(sColor,iDoors,iMpg) {
  this.color = sColor;
  this.doors = iDoors;
  this.mpg = iMpg;

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

Problem: 这种方式会导致每个对象都有自己的 showColor() .

2. 混合的构造函数/原型方式
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: 把方法定义在类外部

3. 改进版:将方法封装到类定义里面:
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)