日期:2014-05-16  浏览次数:20377 次

Js构造函数&工厂函数
//1,工厂函数&构造函数

//例1。

//工厂方式:

function CreateCar()

{

  var tempCar = new Object;

  tempCar.color = "red";

  tempCar.doors = 4;

  temCar.mpg = 23;

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

}

 

//构造函数:

function Car(sColor,Doors,Mpg)

{

  this.color = sColor;

  this.doors = Doors;

 this.Mpg = mpg;

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

}

//例2 区别

//工厂函数 :
              var car = CreateCar();

                     car.showColor();

//构造函数:
            var car = new Car("red",23,1);

                  car.showColor();

 

 //例3 混合构造函数(原型方式)

function Car(sColor,Doors,Mpg)

{

  this.color = sColor;

  this.doors = Doors;

 this.Mpg = mpg;

this.drivers = new Array("mike","sue");

}

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

 

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

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

car1.drivers.push("mart");

?