admin管理员组文章数量:1314246
I know the "self" magic. But look at this snippet from nodejs(not plete).
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?
I know the "self" magic. But look at this snippet from nodejs(not plete).
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?
Share Improve this question asked Apr 18, 2013 at 5:16 Alvin CaoAlvin Cao 5772 gold badges5 silver badges11 bronze badges 2-
I assume it's used only because of convention and unity with the rest of the code. Using
this
in one place might just be an oversight. – JJJ Commented Apr 18, 2013 at 5:18 -
1
since
self
is set tothis
they're the same variable. I'm not sure why the author mixes the two. – Andrew Klatzke Commented Apr 18, 2013 at 5:24
1 Answer
Reset to default 4In 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.
本文标签: nodejsAbout this and self in javascriptStack Overflow
版权声明:本文标题:node.js - About this and self in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741963477a2407415.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论