ES6 immediately invoked arrow function

后端 未结 4 1431
梦谈多话
梦谈多话 2020-11-28 02:16

Why does this work in a Node.js console (tested in 4.1.1 and 5.3.0) but doesn\'t work in the browser (tested in Chrome)? This code block should create and invok

相关标签:
4条回答
  • 2020-11-28 02:48

    The reason you're seeing problems like this is that the console itself tries to emulate the global scope of the context you're currently targeting. It also tries to capture return values from statements and expressions you write in the console, so that the show up as results. Take, for instance:

    > 3 + 2
    < 5
    

    Here, it executes as though it were an expression, but you've written it as though it were a statement. In normal scripts, the value would be discarded, but here, the code must be internally mangled (like wrapping the entire statement with a function context and a return statement), which causes all sorts of weird effects, including the problems you're experiencing.

    This is also one of the reasons why some bare ES6 code in scripts works fine but doesn't in Chrome Dev Tools console.

    Try executing this in Node and Chrome console:

    { let a = 3 }
    

    In Node or a <script> tag it works just fine, but in the console, it gives Uncaught SyntaxError: Unexpected identifier. It also gives you a link to the source in the form of VMxxx:1 which you can click to inspect the evaluated source, which shows up as:

    ({ let a = 3 })
    

    So why did it do this?

    The answer is that it needs to convert your code into an expression so that the result can be returned to the caller and displayed in the console. You can do this by wrapping the statement in parentheses, which makes it an expression, but it also makes the block above syntactically incorrect (an expression cannot have a block declaration).

    The console does try to fix these edge cases by being smart about the code, but that's beyond the scope of this answer, I think. You can file a bug to see if that's something they'd consider fixing.

    Here's a good example of something very similar:

    https://stackoverflow.com/a/28431346/46588

    The safest way to make your code work is to make sure it can be run as an expression and inspect the SyntaxError source link to see what the actual execution code is and reverse engineer a solution from that. Usually it means a pair of strategically placed parentheses.

    In short: the console tries to emulate the global execution context as accurately as possible, but due to the limitations of interaction with the v8 engine and JavaScript semantics this is sometimes hard or impossible to solve.

    0 讨论(0)
  • 2020-11-28 02:49

    None of these should work without parentheses.

    Why?

    Because according in the spec:

    1. ArrowFunction is listed under AssignmentExpression
    2. The LHS of a CallExpression must be a MemberExpression, SuperCall or CallExpression

    So an ArrowFunction cannot be on the LHS of a CallExpression.


    What this effectively means in how => should be interpreted, is that it works on the same sort of level as assignment operators =, += etc.

    Meaning

    • x => {foo}() doesn't become (x => {foo})()
    • The interpreter tries to interpret it as x => ({foo}())
    • Thus it's still a SyntaxError
    • So the interpreter decides that the ( must have been wrong and throws a SyntaxError

    There was a bug on Babel about it here, too.

    0 讨论(0)
  • 2020-11-28 02:52

    You need to make it a function expression instead of function definition which doesnt need a name and makes it a valid JavaScript.

    (() => {
      console.log('Ok');
    })()
    

    Is the equivalent of IIFE

    (function(){
       console.log('Ok')
    })();
    

    And the possible reason why this works in Node.js but not in chrome is because its parser interprets it as a self executing function, as this

    function() { console.log('hello'); }();
    

    works fine in Node.js This is a function expression and chrome and firefox and most of the browser interprets it this way. You need to invoke it manually.

    The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

    Regarding the parametrized version, this will work.

    ((n) => {
      console.log('Ok');
    })()
    
    0 讨论(0)
  • 2020-11-28 02:56

    I asked a question like this:

    @getify I’ve this question: to produce an #IIFE pattern we use parans around a function declaration to transform it into a function expression and then invoke it. Now in arrow function IIFEs, why do we need parans?! Isn’t the arrow function already an expression by default?!

    and this is the Kyle Simpson's answer:

    an arrow function is an expr, but we need surrounding parens b/c of "operator precedence" (sorta), so that the final parens to invoke the arrow-IIFE apply to the entire function and not to just the last token of its body.

    x => console.log(x)(4)
    

    vs

    (x => console.log(x))(4)
    

    — getify (@getify) June 12, 2020

    0 讨论(0)
提交回复
热议问题