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

前端 未结 4 1396
后悔当初
后悔当初 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');                
                }
            });
        }
    });
    
    0 讨论(0)
  • 2021-02-01 21:28

    There's no reason why you can't use this directly there (and I would say it would be better for readability if you did).

    However, the var self = this; is often needed in situations like the following (basically, any asynchronous action like event binding, AJAX handlers etc, where the resolution of this is deferred until it equals something else);

    function SeatReservation(name, initialMeal) {
        var self = this;
        self.name = name;
        self.meal = ko.observable(initialMeal);
    
        setTimeout(function () {
            alert(self.name); // otherwise, this is window; use self to keep a reference to the "SeatReservation" instance.
        }, 100);
    }
    
    0 讨论(0)
  • 2021-02-01 21:29

    It is usually done in order to keep a reference to this when the context is changing. It is often used in event handlers or callback functions. But as mentioned before, there is no reason to use it in your specific example.

    You will find more details in the following article: http://www.alistapart.com/articles/getoutbindingsituations

    0 讨论(0)
  • 2021-02-01 21:30

    In your example code there is no reason at all to copy this to a variable.

    It's usually used when the code uses a callback method. Inside the callback method this doesn't reference the object, so you use the variable for that.

    0 讨论(0)
提交回复
热议问题