JavaScript吊装说明 [英] JavaScript hoisting explanation
问题描述
以下摘要之间有什么区别?
What is the difference between below snippets?
var a = 0;
function b(){
a = 10;
return function a(){};
}
b();
console.log(a); // => 10
和
var a = 0;
function b(){
a = 10;
return
function a(){};
}
b();
console.log(a); // => 0
这与JavaScript提升有关,但是我对该概念的理解却给出了完全相反的输出.
It has something to do with JavaScript hoisting, but my understanding of the concept gives exactly the opposite output.
推荐答案
return function a(){};
此处function ...
是一个表达式.准确地说,是命名函数表达式.此处的a
没什么大不了,它只是为匿名函数提供了
Here function ...
is an expression. A named function expression to be precise. The a
here doesn't matter much, it just gives the anonymous function a .name
, but it's still just a function expression that you're returning.
return
function a(){};
这等效于:
return;
function a(){};
此处function a
是声明,而不是表达式.它被吊起,在作用域中创建本地名称a
,遮盖了外部a
. IE.它等效于:
Here function a
is a declaration, not an expression. It is hoisted, creating a local name a
in the scope, shadowing the outer a
. I.e. it is equivalent to:
function b(){
var a = function () {};
a = 10;
return;
}
这篇关于JavaScript吊装说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!