私が見た JavaScript ファイルには次のものがありました:
function Somefunction(){
var that = this;
...
}
これを宣言しthat
て割り当てる目的は何ですか?this
ベストアンサー1
この答えは、まずイラストから始めたいと思います。
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
});
});
私の回答はもともと jQuery を使用してこれを示していましたが、これはわずかに異なります。
$('#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
新しい関数を呼び出してスコープを変更すると が頻繁に変更されるため、 を使用して元の値that
にアクセスすることはできません。 にエイリアスすると、 の元の値にアクセスできますthis
。
個人的には、 をエイリアスとして使用するのは好きではありませんthat
。関数が数行以上ある場合は特に、それが何を参照しているかがほとんど明らかではありません。私は常に、より説明的なエイリアスを使用します。上記の例では、おそらく を使用しますclickedEl
。