假设我有一个处理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}))
}
答案 0 :(得分:1)
标准的bind
方法可以做到这一点:
const requestIdleAndGreet = ({firstName, lastName}) =>
requestIdle(greeting.bind(null, {firstName, lastName}));
bind
的第一个参数是绑定函数的this
值,其余参数绑定参数。