gpt4 book ai didi

javascript - 这种提升如何与 block 范围一起工作?

转载 作者:行者123 更新时间:2023-12-04 11:05:57 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Function declaration in block moving temporary value outside of block?

(1 个回答)



What are the precise semantics of block-level functions in ES6?

(2 个回答)


去年关闭。




我被问到一个问题

{
function foo() {
console.log('A');
}

foo();

foo = 1;

function foo() {
console.log('B');
}

foo = 2;

console.log(foo);
}
console.log(foo);

为什么第三个输出是 1而不是 2 ?

不应有 block 范围 foo正在创建,因为没有 let也不是 const在那个街区。但是第二个 foo输出为 2表示确实有另一个引用 foo已经被创造了。
到底是怎么回事?

P.S. I'm using Chrome Version 89.0.4389.90 (Official Build) (x86_64).

最佳答案

根据web compat semantics在函数声明的地方,被阻塞的作用域变量的值被绑定(bind)到外部作用域²。这段代码相当于:

let outerFoo; // the functions create a binding outside of the scope

{
let innerFoo; // but also inside
// due to hoisting, functions get bound before any code get's executed:
innerFoo = function foo() {
console.log('A');
};
innerFoo = function foo() {
console.log('B');
};

// At the place of the function declaration, the variable leaves the scope
/* function foo() {
console.log('A');
} */
outerFoo = innerFoo;

innerFoo();

innerFoo = 1;

// this also applies to the second declaration
/* function foo() {
console.log('B');
} */
outerFoo = innerFoo;

innerFoo = 2;

console.log(innerFoo);
}
console.log(outerFoo);

²这基本上就是规范描述的方式:
When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
a. Let fenv be the running execution context's VariableEnvironment.
b. Let benv be the running execution context's LexicalEnvironment.
c. Let fobj be ! benv.GetBindingValue(F, false).
d. Perform ! fenv.SetMutableBinding(F, fobj, false).

该规范还指出:

Prior to ECMAScript 2015, the ECMAScript specification did not define the occurrence of a FunctionDeclaration as an element of a Block statement's StatementList. However, support for that form of FunctionDeclaration was an allowable extension and most browser-hosted ECMAScript implementations permitted them. Unfortunately, the semantics of such declarations differ among those implementations. Because of these semantic differences, existing web ECMAScript code that uses Block level function declarations is only portable among browser implementation if the usage only depends upon the semantic intersection of all of the browser implementations for such declarations


所以 Safari 可能会按照它一贯的方式来做,而 Chrome(和 Firefox)则遵循规范。

关于javascript - 这种提升如何与 block 范围一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66756997/

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