node.js - About this and self in javascript -
i know "self" magic. @ snippet 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 understanding must use self create closure. here there no closures in these lines author use both after assigning self. make difference here?
in you've shown in particular code example, there no reason have self
variable because there no other function scopes might need access original value of this
.
some developers have consistent methodology or convention create local variable self
, assign value of this
have use, if needed, in closures. self
variable can minimized smaller this
because can renamed 1 character variable name, this
cannot renamed.
in case, functionality here not affected if self
removed , this
used in particular method.
my own personal convention define self
if needed same logic use other local variables , use inside closure needed.
Comments
Post a Comment