为什么闭包可以连接字符串而不是数组?

时间:2018-08-15 12:04:53

标签: javascript closures arrow-functions spread-syntax

我正在对闭包进行更深入的了解,但我遇到了一个谜:

我知道为什么这样工作-闭包位于makeNewValleyGirls的本地函数allGirls中,并相应地进行更新:

const makeNewValleyGirls = () => {
  let addedGirls = [];
  const allGirls = (...girls) => {
    addedGirls = [...addedGirls, ...girls]; //closure stored and updated
    return addedGirls;
  }
  return allGirls;
}

const addGirls = makeNewValleyGirls();

const addMoreValleyGirls = addGirls('Barbie');
const evenMoreValleyGirls = addGirls('Stacy');
//evenMoreValleyGirls prints ["Barbie", "Stacy"]

这行不通-

const makeNewValleyGirls = () => {
  let addedGirls = [];
  const allGirls = (...girls) => [...addedGirls, ...girls];
  return allGirls;
}
const addGirls = makeNewValleyGirls();

const addMoreValleyGirls = addGirls('Barbie');
const evenMoreValleyGirls = addGirls('Stacy');
//evenMoreValleyGirls only prints 'Stacy'

我认为这是因为隐式返回超出了范围,但是如果我将字符串连接到数组而不是数组,则相同的语法也可以工作:

const makeNewValleyGirls = () => {
  let addedGirls = [];
  const allGirls = (...girls) => addedGirls += ' ' + girls;
  return allGirls;
}

const addGirls = makeNewValleyGirls();

const addMoreValleyGirls = addGirls('Barbie');
const evenMoreValleyGirls = addGirls('Stacy');
//evenMoreValleyGirls prints " Barbie Stacy"

这背后的逻辑是什么?

0 个答案:

没有答案