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

后端 未结 5 2105
我在风中等你
我在风中等你 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

    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();
      } 
     };
    

提交回复
热议问题