悬挂变量有目的吗? [英] Is there a purpose to hoisting variables?
问题描述
最近我已经学习了很多Javascript,并且一直试图了解提升变量的值(如果有的话).
I've been learning a lot of Javascript lately and I've been trying to understand the value (if there is any) of hoisting variables.
我了解(现在)JS是一个两遍系统,它会编译然后执行.另外,我知道var关键字在声明的词法范围内存在",因此,如果在引擎为它分配值之前调用它,为什么它是未定义的".
I understand (now) that JS is a two pass system, it compiles and then executes. Also, I understand that the var keyword 'exists' in the lexical scope it was declared, hence why it's 'undefined' if it's called before it's assigned a value by the engine.
问题是,为什么那还要重要?提升没有提升就无法执行的变量有什么用?我觉得它只是创建了可读性差的代码而没有收获...
The question is, why does that even matter? What use is there to hoisting variables that you can't do without hoisting? I feel like it just creates less-readable code with no gain ...
是否有一个示例,其中说明了吊装变量有用的地方?
is there an example(s) of where hoisting variables is useful?
推荐答案
提升"对于相互递归的函数(以及其他所有以循环方式使用变量引用的函数)都是必需的:
"Hoisting" is necessary for mutually recursive functions (and everything else that uses variable references in a circular manner):
function even(n) { return n == 0 || !odd(n-1); }
function odd(n) { return !even(n-1); }
没有提升"功能,odd
功能将不在even
功能的范围内.不支持它的语言则需要转发声明,它不适合JavaScript语言设计.
Without "hoisting", the odd
function would not be in scope for the even
function. Languages that don't support it require forward declarations instead, which don't fit into JavaScripts language design.
需要它们的情况可能会以您认为的更多出现:
Situations that require them might arise more often that you'd think:
const a = {
start(button) {
…
button.onclick = e => {
…
b.start(button);
};
}
};
const b = {
start(button) {
…
button.onclick = e => {
…
a.start(button);
};
}
};
这篇关于悬挂变量有目的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!