javascript - 使另一个函数在 JS 中只能执行一次的函数
问题描述
我一直在努力创建一个函数,给定另一个函数将使第二个函数只能调用一次。与_.once()
功能不同。
期望的结果如下:
const oneTimeFunction = _.once(function(string) { string.split(''); })
oneTimeFunction('hello')
//returns: 'olleh', and if called again it would have no effect returning the same thing a the original call.
目前这就是我所拥有的:
_.once = function (func) {
var called = 0;
let args = null;
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments,1);
}
return function () {
if (called === 0) {
console.log('being called');
called ++;
if (!args) {
console.log('without apply');
return func.call(arguments);
} else {
console.log('with apply');
return func.apply(this,args);
}
} else {
console.log('this has been called');
return null;
}
};
};
我正在碰壁,因为即使我尝试了所有方法,它也会返回未定义的错误类型。任何帮助,即使是到达它可以调用函数的地方,而不管一次性的规定?谢谢!
解决方案
在阅读您的问题时,我看到您希望始终在后续调用中返回第一个值:
“如果再次调用,返回与原始调用相同的内容将无效。”
所以我相信你想做这样的事情:
function computeOnce(myFn) {
let origVal = undefined;
return function (...args) {
// if this is not set, this is the first call
if (!origVal) {
// execute the function and store it's return value
origVal = myFn(...args);
}
return origVal;
}
}
推荐阅读
- ios - 当 ViewController 可见时 Swift 调用函数
- php - 用零计数替换不匹配或空的 SQL 查询
- javascript - 访问令牌过期时如何在带有 keycloak 的 Nuxt auth 模块(oauth2)中使用刷新令牌
- git - 有没有办法删除所有以前提交的 gpg 标志或用另一个 gpg 密钥辞职
- python - Python中的特定数据类型
- typescript - 使用 TypeScript 和 FirebaseAuthUI 在 Store 中使用 vue-router 进行 Vue 导航
- typescript - TypeScript 不能正确推断函数的确定性返回类型
- css - 是否可以在没有任何 svg 的情况下生成曲线框?
- css - 添加带有边框和集中文本的 Bootstrap 面板
- azure - 将 PySpark Dataframe 写入 Azure Synapse 时面临的问题