问题:
This question already has an answer here:
What are the precise semantics of block-level functions in ES6? 2 answers
This is the example:...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
This question already has an answer here:
This is the example:
function b() {
console.log(f);
{
function f() {}
}
}
b()
I thought it would become:
function b() {
// hoist to function scope
function f() {}
console.log(f); // should output function f
}
or
function b() {
console.log(f); // should output reference error
{
// just hoist to block scope like this
function f() {}
}
}
but it outputs undefined, like var
hoisting. why?
回答1:
{}
creates block scope so
JS engine will interpret your code something like this
function b() {
console.log(f);
{
var f = function f() {};
}
}
b();
So because of block scoping value of f
is not available out of block. and since it is defined as var it is hoisted to parent's scope ( function b's scope ) and turns out to be undefined
If you remove {}
.
function b() {
console.log(f);
function f() {}
}
b()
回答2:
It's due to Hoisting. The function f() {}
is inside a block, therefore console.log(f) cannot access the function f() {}
, that is out of the scope. However, if you keep the console.log(f)
inside the block {}
. Hoisting should work.