简体   繁体   中英

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

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.

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

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

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.

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.

ie

$('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) ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM