Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 713
Oguz Karadenizli Avatar asked Jul 20 '12 10:07

Oguz Karadenizli


People also ask

Why we use var self this?

It's a way of maintaining the scope of "this" inside another scope. "self" is arbitrary, you could call it "foo" if you wanted.

Do we need to use var that this JavaScript?

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).

What is the purpose of using VAR in JavaScript?

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.

What is the difference between self and this in JavaScript?

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.


2 Answers

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);
}
like image 64
Matt Avatar answered Oct 16 '22 17:10

Matt


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

like image 9
Stilltorik Avatar answered Oct 16 '22 16:10

Stilltorik