SORU
3 ŞUBAT 2011, PERŞEMBE


';' JavaScript demek bu = var ne yok?

JavaScript dosyasında gördüm

function Somefunction(){
   var that = this; 
   ... 
}

that ilan ve this atama amacı nedir?

CEVAP
3 ŞUBAT 2011, PERŞEMBE


Bir örnek ile bu cevap başlayacağım:

var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
    // this is a reference to the element clicked on

    var that = this;

    colours.forEach(function() {
        // this is undefined
        // that is a reference to the element clicked on
    });
});

Benim cevabım aslında çok az farklı olan dil eklentisi ile bunu gösterdi:

$('#element').click(function(){
    // this is a reference to the element clicked on

    var that = this;

    $('.elements').each(function(){
        // this is a reference to the current element in the loop
        // that is still a reference to the element clicked on
    });
});

this sık sık yeni bir işlev çağırarak kapsamında değiştirdiğinizde, değişiklikler nedeniyle, bunu kullanarak özgün değer erişebilirsiniz. that Aliasing hala this özgün değeri erişim sağlar.

Şahsen, diğer that kullanımını sevmiyorum. Özellikle fonksiyonları birkaç satır daha uzun ise ona atıfta olduğunu nadiren belli. Benher zamandaha açıklayıcı bir ad kullanın. Benim yukarıdaki örnekler, muhtemelen clickedEl kullanmak istiyorum.

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

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • chickenby

    chickenby

    2 HAZİRAN 2008
  • TechRax

    TechRax

    21 EYLÜL 2009
  • tsweeney79

    tsweeney79

    21 Ocak 2008