【发布时间】:2017-09-03 16:16:18
【问题描述】:
背景
我有一个函数负责生成随机数并使其可用。
"use strict";
module.exports = function(args) {
let {
min,
max,
} = args;
let currNumber = genRandom(min, max);
const genRandom = (min, max) => Math.floor(Math.random() * max) + min;
const getNumber = () => currNumber;
return Object.freeze({
getNumber
});
};
问题
由于我不明白的原因,当我使用 Node.js 7.8 运行此代码时,我收到 genRandom is not defined 的错误。
但如果我将代码更改为:
let currNumber = genRandom(min, max);
const genRandom = (min, max) => Math.floor(Math.random() * max) + min;
到:
const genRandom = (min, max) => Math.floor(Math.random() * max) + min;
let currNumber = genRandom(min, max);
然后就可以了!
我不明白为什么会这样。我以为const 和let 就像var 一样被吊起,但这让我相信我错了。
问题
有人可以解释一下这种行为吗?
【问题讨论】:
-
const或let与var的不同之处在于该变量在声明之前是不可访问的。 -
所以,它们并没有被提升到函数的顶部,对吧?
-
@tsh 您可能想将其发布为答案。
-
仅供参考,使用
var也会导致问题。该变量可能存在,因为它的定义被提升了,但它没有值,直到为其分配值的代码行在您放置它的位置运行。现在,如果您使用function genRandom() {}定义本地函数,那么整个函数定义将被提升。所以,这与let、const或 ES6 无关。不会提升对任何类型变量的赋值。 -
@jfriend00:它会导致 a 问题,但会导致不同的问题。 :-)
标签: javascript node.js ecmascript-6