Why can\'t we directly use this
instead of self
in the following example?
function SeatReservation(name, initialMeal) {
var self =
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);
}