JS混合構造関数と動的プロトタイプ

3482 ワード

      ,         +        
               .
                (  )
 
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"

 
 
        :
function Car(sColor,iDoors,iMpg) {

  this.color = sColor;

  this.doors = iDoors;

  this.mpg = iMpg;

  this.drivers = new Array("Mike","John");

  

  if (typeof Car._initialized == "undefined") {

    Car.prototype.showColor = function() {

      alert(this.color);

    };

    

    Car._initialized = true;

  }

}

どれだけのcarオブジェクトを実装してもショーColor関数は一度だけ初期化されます.
 
 
 
 
.csharpcode.csharpcode pre
{
font-size:small;
カラー:black
font-family:consosolas、「Courier New」、courier、monoospace;
background-カラー:菗菗ffff;
//white-space:pre;*/
)
.csharp code pre{margin:0 em;}
.csharpcode.rem{color=0000 ff}
.csharpcode.kwrd{color=0000 ff}
.csharpcode.str{color=red}
.csharpcode.op{color=0000 c 0}
.csharpcode.preproc{color=red}
.csharpcode.asp{background}
.csharrpcode.html
.csharpcode.atr{color=red}
.csharpcode.alt
{
background-彩色:〹f 4 f 4;
width:100%
magin:0 em;
)
.csharpcode.lnum{color=0000 ff}