【问题标题】:Way to understand this code. How is it working?理解这段代码的方式。它是如何工作的?
【发布时间】:2019-10-12 04:46:43
【问题描述】:
我在 javascript 中探索作用域并开始了解这个问题。我不明白这个问题是如何工作的。
function checkType() {
return foo;
foo = 10;
function foo() {};
var foo = 11;
};
console.log(typeof checkType())
我的问题是javascript编译器如何决定返回函数而不是变量。欢迎任何参考或解释。
【问题讨论】:
标签:
javascript
scoping
hoisting
【解决方案1】:
这就是编译器编译上述代码的方式..
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() 返回函数而不是整数。
注意:因为函数是使用function(){} 语法定义的,所以它
被提升到父函数范围,否则,如果函数是
使用var foo = function() {} 定义,则提升不会
以相同的方式工作,您的函数将返回 undefined。
有关范围界定和提升的更多参考
【解决方案2】:
首先,所有函数声明都在作用域中提升。因此,首先代码将变量foo 移动到作用域的顶部,并将其值初始化为函数。
变量的第二个声明没有被提升,因为函数声明已经被提升了。所以代码和
一样
function checkType() {
var foo = function(){}
return foo;
foo = 10;
foo = 11;
};
【解决方案3】:
当我们运行代码时,它有两个阶段,第一个阶段是creation phase,在这个阶段语法解析器将读取代码并提升函数和变量,第二个阶段是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())