Function Declarations Within Blocks according to the Google JavaScript style guide

元气小坏坏 提交于 2019-11-27 23:17:02

A function is not a block. A block is (for example) what follows a while, for, or if.

First, understand that function declarations (function foo() {}) are hoisted to the top of the scope of their containing function (i.e., you can access a declared functions by name anywhere in the same scope as the declaration).:

foo();
function foo() { }

This out-of-order code is 100% legal because the declaration of foo is hoisted to above the foo() invocation. However, now imagine you have a conditional declaration:

if(false) {
    function foo() { }
}

From a language-design perspective, should foo be hoisted? The program flow will never enter the block, but we customarily hoist all declarations. Due to this confusion, declarations inside blocks are not part of the grammar defined by the ECMAScript spec (though each implementation does support this grammar, but causes a different, nonstandard effect in each).

Having a function inside another function does not carry this confusion:

function bar() {
    function foo() { }
}

It's obvious that foo will be hoisted to the top of bar (whenever it runs).

Thus, your first example is perfectly fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!