如果由于提升变量应该在我的情况下是函数的范围之上,为什么函数首先返回?

托管变量应该在作用域的顶部,这样 displayInstructor 函数上的变量应该在作用域的顶部,但它仍然返回 undefined 为什么?不应该回答应该是变量值?因为吊起它应该在上面


function displayInstructor(){

    return instructor;

    var instructor = "Loser";

}


精慕HU
浏览 131回答 2
2回答

侃侃无极

根据文档- It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached.变量instructor将被提升到函数的顶部displayInstructor,但是它的值将在到达语句时分配var instructor = "Loser";。该return语句在执行实际赋值代码之前使用,此时变量instructor为undefined.function displayInstructor(){    console.log(instructor) // undefined    return instructor;    var instructor = "Loser";}console.log(displayInstructor());相反,首先分配值,然后返回变量。function displayInstructor() {  var instructor = "Loser";  return instructor;}console.log(displayInstructor());

德玛西亚99

解释器首先遍历代码,创建变量并将它们分配给 undefined。此函数将返回 undefined 因为返回将在赋值之前起作用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript