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

后端 未结 5 2103
我在风中等你
我在风中等你 2021-02-19 07:30

I\'m reading the source from mongoose

Collection.prototype.onOpen = function () {
  var self = this;
  this.buffer = false;
  self.doQueue();
};
<
5条回答
  •  星月不相逢
    2021-02-19 08:09

    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.

提交回复
热议问题