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

  • 8bitdigitaltv

    8bitdigitalt

    31 AĞUSTOS 2011
  • How To Cook That

    How To Cook

    16 NİSAN 2011
  • Chaîne de TheMoustic

    Chaîne de T

    5 Kasım 2006