I\'m reading the source from mongoose
Collection.prototype.onOpen = function () {
var self = this;
this.buffer = false;
self.doQueue();
};
<
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.
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();
}
};
self is a copy of 'this',but it always refer to the right object,and 'this' may not.
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.
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.