为什么不能使用本身在所述变量之后初始化的箭头函数来初始化变量?

时间:2019-09-17 10:47:09

标签: javascript

我有这个id变量,正在使用“ guidGenerator”函数进行初始化

const id = `numberinput#${guidGenerator()}`;

我的问题源于同一功能的两个版本之间的行为差​​异,一个版本使用function关键字创建,另一个版本使用() =>

两个功能:

function guidGenerator() {
  const S4 = function() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}

const guidGenerator = () => {
  const S4 = function() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}

相关代码:

const id = `numberinput#${guidGenerator()}`;

/*
function guidGenerator() {
  const S4 = function() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}
*/

const guidGenerator = () => {
  const S4 = function() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}

如果我使用常规函数,则一切正常,但如果使用箭头函数,则会出现以下错误:

  

ReferenceError:初始化之前无法访问'guidGenerator'

我知道我可以通过简单地将 id 变量初始化放在函数后使其与箭头函数一起使用,但是我的问题是为什么它与常规函数一样工作而不与常规函数一起工作箭头功能。

0 个答案:

没有答案
相关问题