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

2019-03-09 21:32发布

问题:

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

function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);
}

After responses, I've learned:

Yes, there is no need if there is no context switch in class.

But I will use this approach as "convention" although there is no need.

回答1:

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


回答2:

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



回答3:

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.



回答4:

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