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

  • Carlos Delgado

    Carlos Delga

    21 HAZİRAN 2011
  • superemposed

    superemposed

    25 Aralık 2007
  • TotalxLuna

    TotalxLuna

    27 Kasım 2011