包装功能助手

时间:2018-11-06 03:16:12

标签: javascript functional-programming

假设我有一个处理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}))
} 

1 个答案:

答案 0 :(得分:1)

标准的bind方法可以做到这一点:

const requestIdleAndGreet = ({firstName, lastName}) => 
    requestIdle(greeting.bind(null, {firstName, lastName}));

bind的第一个参数是绑定函数的this值,其余参数绑定参数。