Read the statement by Michael Teeuw here.
Why are people doing this: var self = this?
-
I keep seeing modules doing the following:
socketNotificationReceived: function(notification, payload) { var self = this; if (notification === "CURRENT_STATUS") { ...
- Can someone explain why they do this?
- What make
this
change so that you need to save it?
-
@E3V3A said in Why are people doing this: var self = this?:
var self = this
this
can change. When it’s called first, it’s one thing and when you think you need the same thing again,this
might be something else already. So you temporarily store the firstthis
in the varself
. That way it’s the same thing when you need it later again. -
@doubleT Hi, yeah I figured that much. But in the cases where I have seen it, it is not obvious what would change it outside that function. In the example, from above, was taken from the MMM-Remote-Control, where it’s done all over the place. So if you are that paranoid that it can change that easily, it could as well change in between function calls, before even setting
var self=this
? Leading to the question of:- What is the exact scope of
this
? - Does the core MM change it or use it as well?
- What is the exact scope of
-
-
@ninjabreadman Great Find! Exactly what I needed. That it seem a great lesson on this.
In the reference…
To fix the problem with using this inside the anonymous function passed to the "forEach" method, we use a common practice in JavaScript and set the this value to another variable before we enter the "forEach" method.