gpt4 book ai didi

javascript - 为什么回调函数没有在 JavaScript 中提升?

转载 作者:行者123 更新时间:2023-11-29 10:09:14 30 4
gpt4 key购买 nike

我理解 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')
})
}

最佳答案

有问题的行为不限于命名回调。这是任何命名函数表达式的工作方式。请考虑以下事项:

function foo() {
(function baz() { });
console.log(typeof baz);
}

> foo()
< undefined

baz 在其主体之外是不可访问的。所以这是一个不同于提升的问题。

关于javascript - 为什么回调函数没有在 JavaScript 中提升?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36660703/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com