简体   繁体   English

什么在函数中创建函数?

[英]What creates a function in a function?

Why is the result of the following code 1 and not 10? 为什么以下代码1的结果而不是10? Why doesn't the function bar() change the value, even though there is a return statement. 为什么即使有return语句,函数bar()也不更改值。

var foo = 1;
function bar() {
  foo = 10;
  return;

  function foo() {}
}

bar();
alert(foo);

This is because while compiling the foo function declaration inside bar moves on the top of the bar . 这是因为在编译foo内部函数声明bar上的顶级运动bar Like this 像这样

var foo = 1;
function bar() {
  function foo() {}
  foo = 10;
  return;
}

bar();
alert(foo);

Read about hoisting in JS . 阅读有关使用JS进行吊装的信息 And here in the "var hoisting" section 这里的“VAR提升”部分

This is because function definitions are hoisted to the top of their scope, so the foo assignment inside bar() is actually referring to the local function that has an empty body. 这是因为function定义被提升到其作用域的顶部,因此bar()的foo赋值实际上是指具有空主体的局部函数。

You can read more about this here 您可以在此处了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM