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

后端 未结 5 2109
我在风中等你
我在风中等你 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 07:52

    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.

提交回复
热议问题