Freewind
Freewind

Reputation: 198248

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

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.

Upvotes: 14

Views: 2461

Answers (5)

Srikanth Kshatriy
Srikanth Kshatriy

Reputation: 444

Just to give more clarity to @richard said earlier,

Collection.prototype.onOpen = function () {
  var self = this;
  this.buffer = false;
  this.onclick = function(){
     //do some other operations here
     //if you refer `this` here then, `this` will refer to present function not the above. so to make sure it is referring to exact object people pass this to `me` or `self`   
     self.doQueue();
  } 
 };

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318518

Most likely the developer wanted consistency, but failed at doing so.

Otherwise you'd be using this in some functions, self in other functions and a mix of both in other functions, depending on where you use the object and if you use nested functions/callbacks.

By always assigning this to self and then using the latter you have one additional assignment at the very beginning of each function but you always use self to access the object.

However, what the developer did in the code you posted does not make much sense. He should either use self or this both times instead of a mix that is not even necessary.

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

The only reason you would usually do that is if the call to doQueue() is inside a block that will change the value of this such as another function.

In this case however it doesn't serve any purpose and was probably a remnant of older code that was not changed back.

Upvotes: 2

Ryan Yiada
Ryan Yiada

Reputation: 4769

self is a copy of 'this',but it always refer to the right object,and 'this' may not.

Upvotes: -2

Richard
Richard

Reputation: 8280

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.

Upvotes: 19

Related Questions