gpt4 book ai didi

javascript - 如何访问拥有 Function.prototype 扩展的函数?

转载 作者:行者123 更新时间:2023-12-02 19:12:44 25 4
gpt4 key购买 nike

我正在尝试创建一个函数扩展来消除任何函数的反跳(如果快速连续多次调用该函数,则仅执行一次,并最好返回一个缓存值)。

我打算在 UI 框架内使用它,但我希望它是可移植的。到目前为止我的代码如下:

Function.prototype.debounce = function()
{
var originalFunction = this; //this should be 'clickButton' in the example implementation
var originalArguments = arguments;

function debouncedFunction()
{
var originalContext = this;
return originalFunction.apply(originalContext,originalArguments)
}

if(this.__DEBOUNCEDVALUE === undefined)
{
this.__DEBOUNCEDVALUE = debouncedFunction();
if(this.__DEBOUNCEDVALUE === undefined)
this.__DEBOUNCEDVALUE = null;
setTimeout(function(){originalFunction.__DEBOUNCEDVALUE = undefined},1000);
}

return this;
}

接下来,我定义了一个通用函数“clickButton”,如下所示:

function clickButton()
{
document.getElementById('log').innerHTML += "<br/>Clicked "+arguments[1];
return "some value";
}

当我调用clickButton.debounce(3,4)时,它起作用了。它每秒只记录一次到文档,但每次调用时都会返回。

但是,当我通过监听器 (buttons[i].addEventListener('click',clickButton.debounce)) 调用它时,originalFunction 变量设置为按钮,而不是功能。没什么大惊喜。在此示例中,如何从 debounce 中获取对 clickButton 的引用?

编辑:我尝试切换到使用defineProperty,它允许我在访问时保存上下文和函数。不幸的是,这并不适用于所有情况(将其放入 Sencha Touch 中的点击处理程序会导致在 Window 范围内调用函数)。这已经很接近了,但仍然令人无法接受。

Object.defineProperty(Function.prototype,'debounce',{get: function()
{
var originalFunction = this;
var execute = function()
{
if(originalFunction.__DEBOUNCEDVALUE === undefined)
{
originalFunction.__DEBOUNCEDVALUE = originalFunction.apply(this,arguments);
if(originalFunction.__DEBOUNCEDVALUE === undefined)
originalFunction.__DEBOUNCEDVALUE = null;
setTimeout(function()
{
originalFunction.__DEBOUNCEDVALUE = undefined;
console.log("Reset");
},5000);
}
else
console.log("Return cached value");

return originalFunction.__DEBOUNCEDVALUE;
}
return execute;

}});

最佳答案

这只能通过某种将函数对象绑定(bind)到debounce的方法来完成。

一种方法是使用.bind

buttons[i].addEventListener('click',clickButton.debounce.bind(clickButton)),
<小时/>

另一种方法是传递一个关闭 clickButton 的匿名函数。

buttons[i].addEventListener('click',function(e) {
return clickButton.debounce.apply(clickButton, arguments);

// The following would suffice for this example:
// return clickButton.debounce(e);
}),
<小时/>

但是除了这些技术之外,debounce 在传递给 addEventListener 时将不会存储引用它的对象。

关于javascript - 如何访问拥有 Function.prototype 扩展的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13499772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com