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.
You’re right, in this instance they could have simply used
this.The use of
meorselfis a bit of a hack to ensure the correct context ofthisis used, as within JavaScript the scope ofthisis variant. If for example you have an event trigger a function within your class,thiswould 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 usemeorselfto ensure they’re referring to the correct object…this, as in the actual object.