Is there a purpose to hoisting variables?

前端 未结 3 877
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 23:24

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

3条回答
  •  甜味超标
    2020-12-16 23:59

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

提交回复
热议问题