3 回答
TA贡献1777条经验 获得超10个赞
这是由于所谓的“吊装”。
基本上,当您使用 时,JavaScript 会将函数移动到作用域的顶部,以便您可以在初始化之前访问它。使用 let 不会这样做。function
func_1();
function func_1() {
console.log("Thing");
}
func_2(); // will cause an error
let func_2 = () => console.log("Thing");
细节:从技术上讲,一切都是吊装的,但是在你到达他们的生产线之前不要初始化。如果使用 ,则该变量的开头为letconstvarundefined
console.log(aa); //undefined
var aa = "hello";
console.log(aa); //hello
console.log(bb) // error
let bb = "hello";
旁注(这部分不是上述问题的解决方案):1.你应该使用而不是,因为我不认为你需要改变函数的值。2.这些声明之间的另一个区别是关键字的值(在这种情况下是相同的,但可以不同)。我不会在这里解释它,如果你做更多的Javascript,你可能会遇到它,所以值得研究。constletthis
TA贡献1898条经验 获得超8个赞
let pickColor = ...行为类似于普通的变量声明 + 赋值。
仅当执行实际的代码行时,才会完成赋值。=
仅当调用发生在声明之后且在可见范围内时,才能调用以这种方式定义的函数。
相反,定义是完全“吊起”的,这意味着它们的行为就像在JS块的顶部定义一样,并且可以被称为“在”它们的定义之前。function()
示例灵感来自 http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html:
isItHoisted();
function isItHoisted() {
console.log("Yes! This function declaration acts the same as if it was declared _before_ the call.");
}
isThisOtherOneHoisted(); // throws an ReferenceError if used before it is assigned
let isThisOtherOneHoisted = () => console.log("Javascript sees that the name exists, but the assignment has not been done.");
/**
like :
There is this variable isThisOtherOneHoisted defined later, just so you know.
isThisOtherOneHoisted(); // error, variable does not even containt a function yet
isThisOtherOneHoisted = () => console.log(...)
*/
作为其他细节,javascript仍然“看到”它在初始化之前被使用,所以这就是为什么错误消息与你使用根本不存在的变量不同。
对于任何变量,仅针对变量存在的事实,都会提升声明。的赋值仅在写入的位置执行。=
TA贡献1911条经验 获得超7个赞
函数声明
function pickColor(){...}
与使用 声明的任何变量一起移动到作用域的顶部(首先提升)。var
其中,仅当解释器遇到该行代码时,才会访问声明的 as 函数表达式。let
示例 -
let two = () => {
console.log('something else');
}
var x = 'demo'
let y = 'demo123'
function one() {
console.log('something');
};
function three(){
one();
}
变量 , 将一旦执行开始,就会移动到作用域的顶部,xfunction one(){...}function three(){...}
x,直到为该行分配值 。undefinedx = 'demo'x'demo'
变量未启动或分配任何值,直到行y
let y = 'demo123'
因为 用于启动变量,因此使用 启动的函数表达式也是如此。letlet
添加回答
举报
