Destructuring a function from object ( Date Object )

后端 未结 2 1709
甜味超标
甜味超标 2021-01-27 00:45

If i want to destruct an Object i would do :

2条回答
  •  自闭症患者
    2021-01-27 01:16

    It's likely not worth it, but you could write a function to help you destructure methods from an object. Here bindMethods does this, using helper allKeys, which collects the keys from the entire prototype chain of an object and which in turn depends on walkPrototypeChain. They could obviously be folded into a single function if desired.

    const walkPrototypeChain = (process, init, finish) => (obj) => {
      let currObj = obj, currRes = init();
      do {
        currRes = process(currRes, currObj)
      } while (currObj = Object.getPrototypeOf(currObj))
      return finish(currRes)
    }
    
    const allKeys = walkPrototypeChain(
      (set, obj) => {Object.getOwnPropertyNames(obj).forEach(k => set.add(k)); return set},
      () => new Set(),
      s => [...s]
    )
    
    const bindMethods = (obj) => allKeys(obj).reduce(
      (o, n) => typeof obj[n] == 'function' ? ({...o, [n]: obj[n].bind(obj)}) : o, 
      {}
    )
    
    const date = new Date()
    const {getDate, getFullYear} = bindMethods(date) // or any other date function
    
    console.log(getDate())
    console.log(getFullYear())

提交回复
热议问题