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

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

    0 讨论(0)
  • 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();
      } 
     };
    
    0 讨论(0)
  • 2021-02-19 07:52

    self is a copy of 'this',but it always refer to the right object,and 'this' may not.

    0 讨论(0)
  • 2021-02-19 07:57

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题