假设我有一个处理 requestIdleCallBack
的函数和一个问候函数:
const requestIdle = (func, timeout) => {
if ('requestIdleCallback' in window) {
timeout = timeout ? {timeout} : null
return window.requestIdleCallback(func, timeout)
} else {
func()
return null
}
}
const greeting = ({firstName, lastName}) => {
console.log(`Hello ${firstName} ${lastName}`)
}
然后,我想在空闲时调用greeting
函数。所以代码是:
const requestIdleAndGreet = ({firstName, lastName}) => {
requestIdle(() => greeting({firstName, lastName}))
}
这是我的问题:是否有一个 vanilla/jquery/lodash... 助手可以充当 greeting({firstName, lastName})
的“包装”函数?像这样的事情:
const wrapper = (func, ...args) => {
return () => {
func(...args)
}
}
const requestIdleAndGreet = ({firstName, lastName}) => {
requestIdle(wrapper(greeting, {firstName, lastName}))
}
最佳答案
标准的bind
方法可以做到这一点:
const requestIdleAndGreet = ({firstName, lastName}) =>
requestIdle(greeting.bind(null, {firstName, lastName}));
bind 的第一个参数是绑定(bind)函数的 this 值,其余参数绑定(bind)参数。
关于javascript - 包装函数帮助器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53165293/