I know the "self" magic. But look at this snippet from nodejs(not complete).
Socket.prototype.connect = function(options, cb) {
......
var self = this;
var pipe = !!options.path;
if (this.destroyed || !this._handle) {
this._handle = pipe ? createPipe() : createTCP();
initSocketHandle(this);
}
if (typeof cb === 'function') {
self.once('connect', cb);
}
timers.active(this);
self._connecting = true;
self.writable = true;
......
}
It is my understanding that we must use self to create a closure. Here there is no closures in these lines but the author use both after assigning this to self. Does it make any difference here?
In what you've shown in this particular code example, there is no reason to even have the self variable because there are no other function scopes that might need access to the original value of this.
Some developers have a consistent methodology or convention to create a local variable like self and assign it the value of this just so that they have it to use, if needed, in closures. The self variable can also be minimized smaller than this because it can be renamed to a one character variable name, but this cannot be renamed.
In any case, the functionality here would not be affected if self was removed and only this was used in this particular method.
My own personal convention is to only define self if it is actually needed which is the same logic I use for other local variables and then I only use it inside the closure where it is needed.