Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assign `this` to `self` and run `self.method()`?

Tags:

javascript

I'm reading the source from mongoose

Collection.prototype.onOpen = function () {
  var self = this;
  this.buffer = false;
  self.doQueue();
};

I don't understand why the author assigns this to self and runs self.doQueue(). Why not just run:

this.buffer = false;
this.doQueue();

I'm new to javascript, thanks for help.

like image 831
Freewind Avatar asked May 14 '12 09:05

Freewind


1 Answers

You're right, in this instance they could have simply used this.

The use of me or self is a bit of a hack to ensure the correct context of this is used, as within JavaScript the scope of this is variant. If for example you have an event trigger a function within your class, this would be different, and wouldn't be your object that houses the function, but instead the object that called the function. To resolve this people often use me or self to ensure they're referring to the correct object... this, as in the actual object.

like image 53
Richard Avatar answered Oct 03 '22 11:10

Richard