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 to this they're the same variable. I'm not sure why the author mixes the two. – Andrew Klatzke Commented Apr 18, 2013 at 5:24
Add a ment  | 

1 Answer 1

Reset to default 4

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.

本文标签: nodejsAbout this and self in javascriptStack Overflow