ozz ozz - 2 months ago 6
Javascript Question

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.

Answer

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