SORU
8 EKİM 2009, PERŞEMBE


JavaScript statik değişkenler

Nasıl Javascript statik değişkenler oluşturabilir miyim?

CEVAP
8 EKİM 2009, PERŞEMBE


JS fonksiyonları da özellikleri var ki nesneleri olduğu gerçeğini de yararlanın.

Örneğin, (şimdi kayboldu) madde verilen alıntı 4**:

function countMyself() {
    // Check to see if the counter has been initialized
    if ( typeof countMyself.counter == 'undefined' ) {
        // It has not... perform the initialization
        countMyself.counter = 0;
    }

    // Do something stupid to indicate the value
    alert(  countMyself.counter);
}

Eğer bu işlevi birkaç kez çağırırsanız, artırılır sayaç göreceksiniz.

Ve bu muhtemelen global bir değişken ile genel ad poluting çok daha iyi bir çözümdür.


Ve burada başka bir olası çözüm, kapatma : Trick to use static variables in javascript :

var uniqueID = (function() {
   var id = 0; // This is the private persistent value
   // The outer function returns a nested function that has access
   // to the persistent value.  It is this nested function we're storing
   // in the variable uniqueID above.
   return function() { return id  ; };  // Return and increment
})(); // Invoke the outer function after defining it.

Sen neden aynı tür dışında ... ki, bu sefer, artan değeri, yerine görüntülenen döndürülür.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • CZTUTORIALS

    CZTUTORIALS

    28 Ocak 2011
  • DroidModderX ROOT Master

    DroidModderX

    14 ŞUBAT 2011
  • SegaAmerica

    SegaAmerica

    5 Mart 2008