gpt4 book ai didi

javascript - 为什么 TS 提示函数体内的函数声明

转载 作者:行者123 更新时间:2023-11-30 08:27:20 25 4
gpt4 key购买 nike

我从 TS 收到这个错误:

enter image description here

错误发生的原因很清楚:

function outer(){

if (true) {
function inner(){ // nested function declaration

}
}
}

但我的问题是 - 为什么 TS 会提示 - 是否有一些技术原因我应该在转译到 ES5 时避免嵌套函数声明?

函数表达式会是更好的选择吗?为什么?

最佳答案

Would a function expression be a better choice

是的。以下是要走的路:

function outer() {
if (true) {
const inner = function() { // OK
}
}
}

Why?

  • ES 模块默认处于严格模式。
  • 严格模式不允许在 block 中声明函数

它被禁止的原因包含在 original JavaScript specification 中.简短版本:实现之间的行为不一致

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 differences, 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.

所以当严格模式(ES5)出现时,它就被禁止了。

关于javascript - 为什么 TS 提示函数体内的函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43484701/

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