admin管理员组

文章数量:1423163

I have this error from TS:

It's pretty clear why the error occurs:

function outer(){

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

       }
   }   
}

but my question is - why does TS plain about that - is there some technical reason I should avoid nested function declarations when transpiling to ES5?

Would a function expression be a better choice, and why?

I have this error from TS:

It's pretty clear why the error occurs:

function outer(){

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

       }
   }   
}

but my question is - why does TS plain about that - is there some technical reason I should avoid nested function declarations when transpiling to ES5?

Would a function expression be a better choice, and why?

Share Improve this question edited Apr 19, 2017 at 5:40 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Apr 19, 2017 at 1:23 Alexander MillsAlexander Mills 101k166 gold badges538 silver badges919 bronze badges 2
  • 2 Possible Duplicate: stackoverflow./questions/10069204/… – SoEzPz Commented Apr 19, 2017 at 2:03
  • Some useful links also here: stackoverflow./questions/33359840/… – Jevgeni Commented Apr 19, 2017 at 2:40
Add a ment  | 

1 Answer 1

Reset to default 8

Would a function expression be a better choice

Yes. The following is the way to go:

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

Why?

  • ES modules are in strict mode by default.
  • strict mode does not allow function declarations in blocks

Reason why it was disallowed is covered in the original JavaScript specification. Short version: The behaviour was inconsistent between implementations.

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 remended 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.

So when strict mode came into being (ES5) it made it disallowed.

本文标签: javascriptWhy TS complains with function declarations inside function bodyStack Overflow