托管变量应该在作用域的顶部,这样 displayInstructor 函数上的变量应该在作用域的顶部,但它仍然返回 undefined 为什么?不应该回答应该是变量值?因为吊起它应该在上面function displayInstructor(){ return instructor; var instructor = "Loser";}
2 回答
侃侃无极
TA贡献2051条经验 获得超10个赞
根据文档- 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());
添加回答
举报
0/150
提交
取消