提供“此"信息的方式到全球范围? [英] Way to provide "this" to the global scope?
问题描述
我正在在此stackoverflow帖子中找到的debounce
函数.这是一个允许节流请求的承诺.
I'm working with a debounce
function found here in this stackoverflow post. It's a promise that allows for throttling requests.
当将debounce函数嵌套在一个函数中时,由于某种原因它将无法工作,因为对请求的setTimeout
调用似乎一次全部发送了.我认为需要直接引用.
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)
}
这是应该使用的方式
var bounced = debounce(mockRequest, 800, 5)
问题是我正在创建一个这样的API对象,但两个选项都不起作用
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
我正在寻找某种使用this
的方式,而不是直接调用debounce方法.
I'm looking for some way to use this
and not call the debounce method directly.
理想的情况是这样
API.prototype.request = function(){
return this.debounce(this.makeRequest, 1000, 2)
}()
推荐答案
我认为应该
API.prototype.request = API.prototype.debounce(API.prototype.makeRequest, 1000, 2)
在创建方法时,您既没有实例(this
)也没有options
对象.那些提供给debounced
函数,在其中存储它们,然后(可能稍后)用于调用提供的函数.
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.
顺便说一句,将debounce
放在API的原型上可能没有任何意义-这是一个通用的辅助方法,而不是实例方法.还要注意,当您使用debounce()
原型方法时,您的所有 all 调用将被 global 进行去抖动.如果您希望每个API实例只有一个队列,则最好这样做
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
这篇关于提供“此"信息的方式到全球范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!