使用循环在全局范围中定义的Redeclare变量

时间:2018-02-21 18:07:10

标签: javascript node.js function loops declare

我正在尝试重新声明在全局范围内定义的变量。我想包装每个函数

const {values, map, each} = require('lodash')

const wrapFnInLog = (fn) => (...input) => {
  console.log({name: fn.name, input})
  const possiblePromise = fn.apply(null, input)
  if (get(possiblePromise, 'then')) {
    return possiblePromise.then(output => {
      console.log({name: fn.name, output})
      return output
    })
  } else {
    console.log({name: fn.name, output: possiblePromise})
    return possiblePromise
  }
}

let a = (arr) => map(arr, i => i.name)
let b = (obj) => a(values(obj))

const provide = [a, b]

provide.forEach(fn => wrapFnInLog(fn))

const example = {
  personTom: {
    name: 'Tom'
  },
  personJerry: {
    name: 'Jerry'
  }
}

b(example)

我希望输出看起来像这样:

{ name: 'b', input: [ { personTom: [Object], personJerry: [Object] } ] }
{ name: 'a', input: [ [ [Object], [Object] ] ] }
{ name: 'a', output: [ 'Tom', 'Jerry' ] }
{ name: 'b', output: [ 'Tom', 'Jerry' ] }

我能够实现这一目标的唯一方法是没有循环,而是通过故意逐个覆盖每个变量。

a = wrapFnInLog(a)
b = wrapFnInLog(b)

我想知道是否可以循环[a, b]并覆盖函数定义,同时将它们保留在全局模块范围内。

1 个答案:

答案 0 :(得分:2)

如已经评论过,您可以使用解构分配一次分配多个变量

let a = (arr) => map(arr, i => i.name);
let b = (obj) => a(values(obj));

[a,b] = [a,b].map(wrapFnInLog);

但与结构变量赋值(let [a,b] = ...)结合使用不同,您必须小心在分配之前编写的内容以及正确分离命令。

因为使用自动分号插入或JS 在一个应该插入分号的地方插入分号,

let a = (arr) => map(arr, i => i.name)
let b = (obj) => a(values(obj))

[a,b] = [a,b].map(wrapFnInLog)

将被解释为

let a = (arr) => map(arr, i => i.name);
let b = (obj) => {
  return a(values(obj))[a,b] = [a,b].map(wrapFnInLog);
}
//or in other words
let b = (obj) => {
  let tmp1 = a(values(obj));
  a; //the `a,` in something[a,b];
  let tmp2 = [a,b].map(wrapFnInLog);
  tmp1[b] = tmp2;
  return tmp2;
}