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

前端 未结 6 927
后悔当初
后悔当初 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条回答
  •  旧时难觅i
    2020-11-22 01:03

    Here is an example `

    $(document).ready(function() {
            var lastItem = null;
            $(".our-work-group > p > a").click(function(e) {
                e.preventDefault();
    
                var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
                if (item == lastItem) {
                    lastItem = null;
                    $('.our-work-single-page').show();
                } else {
                    lastItem = item;
                    $('.our-work-single-page').each(function() {
                        var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                        if (imgAlt != item) {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                }
    
            });
        });`
    

    So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

    `$(document).ready(function() {
            var lastItem = null;
            $(".our-work-group > p > a").click(function(e) {
                e.preventDefault();
                var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
                if (item == lastItem) {
                    lastItem = null;
                    var that = this;
                    $('.our-work-single-page').show();
                } else {
                    lastItem = item;
                    $('.our-work-single-page').each(function() {
                       ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                        var imgAlt = $(this).find('img').attr('alt'); 
                        if (imgAlt != item) {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                }
    
            });
        });`
    

    .....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

提交回复
热议问题