Why do we need “var self = this” in classes in Javascript?

前端 未结 4 1448
后悔当初
后悔当初 2021-02-01 20:54

Why can\'t we directly use this instead of self in the following example?

function SeatReservation(name, initialMeal) {
    var self =          


        
4条回答
  •  误落风尘
    2021-02-01 21:20

    Based on your example, there is "no" reason for doing this.

    There is however, situations where it will help you, although some may frown upon it's usage.

    i.e.

    $('a.go').click(function(e)
    {
        e.preventDefault();
        if(!$(this).hasClass('busy'))
        {
            $(this).addClass('busy');
            $.ajax(
            {
                success : function(resp)
                {
                    $(this).removeClass('busy');
                },
                error : function()
                {
                    $(this).removeClass('busy');                
                }
            });
        }
    });
    

    In the above, $(this) within the success and error callbacks would not reflect to the link you clicked, as the scope has been lost.

    To get around this, you would do var self = $(this) i.e.

    $('a.go').click(function(e)
    {
        e.preventDefault();
        if(!$(this).hasClass('busy'))
        {
            $(this).addClass('busy');
            var btn = $(this);
            $.ajax(
            {
                success : function(resp)
                {
                    btn.removeClass('busy');
                },
                error : function()
                {
                    btn.removeClass('busy');                
                }
            });
        }
    });
    

提交回复
热议问题