为什么JavaScript中没有挂起回调函数
Why are callback functions not hoisted in JavaScript?
我理解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')
})
}
我发现给出的答案太短,所以这里有一个更规范的解释:
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
也被吊起。但为了保护您免受意外的undefined
s的影响,解释器抛出了一个错误。我认为这是明智的。
有问题的行为不限于命名回调。这是任何命名函数表达式的工作方式。考虑以下内容:
function foo() {
(function baz() { });
console.log(typeof baz);
}
> foo()
< undefined
baz
在其体外是不可接近的。所以这是一个不同于吊装的问题。
相关文章:
- Javascript点击事件回调不起作用
- STOMP web套接字回调不'不起作用
- Angular Js 尝试从主按钮回调动态更改模态文本并且不起作用
- 为什么JavaScript中没有挂起回调函数
- socket.io回调函数不起作用
- 如果我移除animateTo参数,.remove()回调函数将不起作用
- 构建Ajax调用数组时,JQueryAjax成功回调不起作用
- 挂起的回调:在每次回调返回之前返回响应
- Javascript中的AJAX-命名回调;不起作用
- JQuery Smart Spinner:回调属性不起作用
- 类似FaceBook的按钮回调不起作用
- jQuery地址在回调中不起作用
- 回调事件不起作用-使用猫头鹰旋转木马
- spawn() 函数的“关闭”回调在 grunt 插件中不起作用
- Javascript回调函数不起作用
- 使用回调的递归Javascript函数不起作用
- 从回调中调用函数会导致节点应用挂起
- 猫鼬查询在回调后挂起
- 护照身份验证回调挂起
- 在promise挂起时延迟执行的回调函数