js 定义类或对象

时间:2021-01-30 19:55:30

1.工厂方式 定义通用类

function createObject(coord,elevation){
  var obj = new Object();
  obj.coord = coord;
  obj.elevation = elevation;
  obj.getCoord = function(){
    return this.coord;
  };
  obj.getElevation = function(){
    return this.elevation;
  }
  return obj;

}

var obj = new createObject();

2.构造函数方式

例:

function Car(sColor,iDoors,iMpg) {
  this.color = sColor;
  this.doors = iDoors;
  this.mpg = iMpg;
  this.showColor = function() {
    alert(this.color);
  };
}

var oCar1 = new Car("red",4,23);

var oCar2 = new Car("blue",3,25);


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

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


var oCar1 = new Car("red",4,23);
var oCar2 = new Car("blue",3,25);

oCar1.drivers.push("Bill");

alert(oCar1.drivers); //输出 "Mike,John,Bill"
alert(oCar2.drivers); //输出 "Mike,John"