我理解JavaScript中变量和函数声明的概念,这些变量和函数声明被悬挂在封闭范围的顶部。但是如果我有一个命名的回调函数,它就不会被挂起。我不明白为何会这样。我有下面的链接中的代码来解释这个场景
示例:
function enclosingScope () {
var b;
function inner (def) {
def();
}
var a = 2;
}
// After hoisting due to compilation, the above changes to
function enclosingScope () {
// Function declarations are hoisted before variables
function inner (def) {
def();
}
var b, a;
a = 2
}
// But if I have a named callback, will that be hoisted?
function enclosingScope () {
function inner (def) {
def();
}
var b, a;
a = 2
inner(function cb () {
console.log('Test callback hoisting')
})
}发布于 2016-04-16 06:28:56
所讨论的行为不限于命名回调。这是任何命名函数表达式的工作方式。请考虑以下几点:
function foo() {
(function baz() { });
console.log(typeof baz);
}
> foo()
< undefinedbaz在其身体之外是不可访问的。所以这是一个不同于吊装的问题。
发布于 2016-05-29 09:27:02
我发现给出的答案太短了,所以这里有一个更规范的解释:
Javascript区分函数声明
function f() {}和函数表达式
var f = function () {} // anynomous function or lambda
var g = function h() {} // named function expression函数声明是语句,而函数表达式是.,你猜怎么着?是啊表情。请注意,命名函数表达式的名称(给定示例中的h)只能在函数体(给定示例中的g )中访问。
无论何时将函数声明嵌套在括号中,它都会自动转换为表达式。这意味着您的function cb () {...}只是一个命名的函数表达式。但是您没有将它赋值给一个变量,而是将它作为参数传递给inner。
当涉及到与函数表达式相关的提升时,只会悬挂指定变量的声明。函数声明的情况并非如此:
console.log(f); // function f
console.log(g); // exists, but undefined
console.log(h); // reference error
function f() {}
var g = function h() {}由于您的示例中的cb没有分配给变量,所以不可能进行提升。
因此,这两条线相当于吊装:
inner(function cb(){});
(function cb(){});奖金: const/let
但是,当您试图调用用const或let声明的函数表达式时,在声明它之前,会引发一个引用错误:
console.log(g); // reference error
const g = function h() {}g也被提升。但是为了防止意外的undefineds,解释器会抛出一个错误。我认为这是明智的。
https://stackoverflow.com/questions/36660703
复制相似问题