理解这段代码的方式。它是如何工作的?

Way to understand this code. How is it working?

我在 javascript 中探索作用域并了解到这个问题。我不明白这个问题是怎么回事。

function checkType() {
  return foo;
  foo = 10;

  function foo() {};
  var foo = 11;
};

console.log(typeof checkType())

我的问题是 javascript 编译器如何决定 return 函数不可变。欢迎任何参考或解释。

这就是编译器编译上述代码的方式..

function checkType() {
  var foo = function() {}; /* function will be hoisted to the top, 
                              and will be assigned to the variable as 
                              the name is the same for the two.. */
  return foo;

  // Code will never reach here as you are returning before this
  foo = 10;
  foo = 11;
};

console.log(typeof checkType());

使用 function() 语法定义的函数将被提升,在这种情况下,嵌套函数将在 checkType() 中被提升,因此 checkType() returns 函数而不是整数。

Note: Because the function was defined using function(){} syntax, it was hoisted to the parent function scope, else, if the function was defined using var foo = function() {} then the hoisting would not have worked in the same way, your function would've returned undefined instead.

有关范围界定和提升的更多参考资料

首先将所有函数声明提升到一个范围内。因此,首先代码将变量 foo 移动到范围的顶部并将其值初始化为函数。

第二个变量声明没有提升,因为函数声明已经提升。所以代码与

相同
function checkType() {
  var foo = function(){}
  return foo;
  foo = 10;

  foo = 11; 
};

当我们运行一段代码时,它有两个阶段,第一个阶段是creation phase,在这个阶段语法解析器将读取代码并提升函数和变量,第二个阶段是execution phase 其中值被分配给提升变量,

A point to note here is function are stored in memory during creation phase as it is where as the variables are hoisted but values are not initialized ( which will be assigned during execution phase )

编译器在提升后会这样对待你的代码

function checkType() {
  var foo = function() {}; //hoisted function
  return foo;
  foo = 10;
  foo = 11;
};

console.log(typeof checkType(), '\nRturned value from function  --->', checkType())

如果你将你的函数定义为变量,它只会被提升但不会被初始化,你可以看下面的例子

function checkType() {
  return foo;
  foo = 10;

  var foo = function foo() {};
  var foo = 11;
};

console.log(typeof checkType(), '\nRturned value from function  --->', checkType())