Way to provide “this” to the global scope?

后端 未结 1 602
悲&欢浪女
悲&欢浪女 2020-12-22 12:32

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

相关标签:
1条回答
  • 2020-12-22 12:48

    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
    
    0 讨论(0)
提交回复
热议问题