这两个函数(箭头函数与函数声明)有什么区别

function pickColor() {

    var random = Math.floor(Math.random() * colors.length);

    return colors[random];

}


let pickColor = () => {

    var random = Math.floor(Math.random() * colors.length);

    return colors[random];

}

当我尝试调用第二个时,我收到一个错误,显示“初始化前无法访问'pickColor'”


慕容森
浏览 185回答 3
3回答

不负相思意

这是由于所谓的“吊装”。基本上,当您使用 时,JavaScript 会将函数移动到作用域的顶部,以便您可以在初始化之前访问它。使用 let 不会这样做。functionfunc_1();function func_1() {    console.log("Thing");}func_2(); // will cause an errorlet func_2 = () => console.log("Thing");细节:从技术上讲,一切都是吊装的,但是在你到达他们的生产线之前不要初始化。如果使用 ,则该变量的开头为letconstvarundefinedconsole.log(aa); //undefinedvar aa = "hello";console.log(aa); //helloconsole.log(bb) // errorlet bb = "hello";旁注(这部分不是上述问题的解决方案):1.你应该使用而不是,因为我不认为你需要改变函数的值。2.这些声明之间的另一个区别是关键字的值(在这种情况下是相同的,但可以不同)。我不会在这里解释它,如果你做更多的Javascript,你可能会遇到它,所以值得研究。constletthis

汪汪一只猫

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 yetisThisOtherOneHoisted = () => console.log(...)*/作为其他细节,javascript仍然“看到”它在初始化之前被使用,所以这就是为什么错误消息与你使用根本不存在的变量不同。对于任何变量,仅针对变量存在的事实,都会提升声明。的赋值仅在写入的位置执行。=

Smart猫小萌

函数声明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'变量未启动或分配任何值,直到行ylet y = 'demo123'因为 用于启动变量,因此使用 启动的函数表达式也是如此。letlet
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript