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.
It's a way of maintaining the scope of "this" inside another scope. "self" is arbitrary, you could call it "foo" if you wanted.
The var keyword is never "needed". However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window object).
The var keyword is used to declare variables in JavaScript. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. Storing a value in a variable is called variable initialization.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With