Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

javascript - Is there a purpose to hoisting variables?

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"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); }

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);
        };
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...