gpt4 book ai didi

javascript - JSHint 的 "function declarations should not be placed in blocks"太宽泛了吗?

转载 作者:搜寻专家 更新时间:2023-11-01 05:11:52 25 4
gpt4 key购买 nike

我理解为什么将函数声明放在 CONDITIONAL block 中是不好的,但是有什么理由建议不要将函数声明放在 standalone block 中(除了可能导致混淆的论点之外因为 JS 不是 block 作用域的):

{
function foo() {};
}

我这样做的原因是为了在 Sublime Text 中实现代码任意部分的代码折叠。

最佳答案

不,这不是“广泛”。这是语言语法。您上面的代码会导致未指定的行为,并且可能在不同的引擎中工作不一致。顺便说一下,它在大多数引擎中的工作方式与您预期的一样,但 ECMAScript 规范在其语法中禁止这样做。

改用表达式:

{
var foo = function(){}; // legal ECMAScript, unlike the declaration
}

引用注释规范:

NOTE: Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable difference, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context. Use variables with function expressions instead.

至于 sublime text,例如你可以折叠带注释的评论。

关于javascript - JSHint 的 "function declarations should not be placed in blocks"太宽泛了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23039964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com