ES6 immediately invoked arrow function

后端 未结 4 1457
梦谈多话
梦谈多话 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

提交回复
热议问题