Way to provide “this” to the global scope?

2019-01-29 07:47发布

问题:

I'm working with a debounce function found here in this stackoverflow post. It's a promise that allows for throttling requests.

The debounce function won't work for some reason when it's nested within a function because the setTimeout calls to the request seem to get sent all at once. It needs to be referenced directly I think.

I can't do something like this because it needs to be referenced directly

function bounced(item){
  return debounce(mockRequest, 800, 5)(item)
}

This is how it should be used

var bounced = debounce(mockRequest, 800, 5)

The problem is I'm creating an API object like this and neither options will work

API.prototype.request = function(options){
  return this.debounce(this.makeRequest, 1000, 2)(options)
}

API.prototype.request = this.debounce(this.makeRequest, 1000, 2) // duh

I'm looking for some way to use this and not call the debounce method directly.

Ideally something like this would be nice

API.prototype.request = function(){
  return this.debounce(this.makeRequest, 1000, 2)
}()

回答1:

I think it should be

API.prototype.request = API.prototype.debounce(API.prototype.makeRequest, 1000, 2)

You have neither an instance (this) nor an options object at the time of creating the method. Those are supplied to the debounced function, where they are stored and then (possibly later) used to call the supplied function.

Btw, it probably makes no sense to place debounce on the prototype of your API - it's a generic helper method, not an instance method. Also notice that when you debounce() the prototype method, all of your calls will be globally debounced. If you want to have one queue per instance of your API, you should better do

function API() {
    // in the constructor:
    this.request = Helpers.debounce(this.makeRequest);
}
API.prototype.makeRequest = function() { … };
// no prototype .request() method