What does 'var that = this;' mean in JavaScript?

前端 未结 6 1018
后悔当初
后悔当初 2020-11-22 00:49

In a JavaScript file I saw:

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

What is the purpose of declaring that and

6条回答
  •  情书的邮戳
    2020-11-22 01:00

    I'm going to begin this answer with an illustration:

    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
        });
    });
    

    My answer originally demonstrated this with jQuery, which is only very slightly different:

    $('#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
        });
    });
    

    Because this frequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this.

    Personally, I dislike the use of that as the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I'd probably use clickedEl.

提交回复
热议问题