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.
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.
i.e.
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.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
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 ofthis
is deferred until it equals something else);