Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is "this" undefined in <script type="module">?

Playing around with ECMAScript Modules just found that calling out this in the "global" scope of a script with type module is undefined but in a normal script, it references to the window object

ES Modules script

    <script type="module">
      console.log(this); // undefined
    </script>

Normal script

    <script>
      console.log(this); // window object
    </script>

Is there any spec about this, or can someone explain me why?

like image 530
Jose Paredes Avatar asked Dec 06 '25 13:12

Jose Paredes


1 Answers

ES6 modules are specced such that their this value is undefined. You can see the spec definition in 8.1.1.5.4 Module Environment Records: GetThisBinding().

8.1.1.5.4 GetThisBinding()

  1. Return undefined.
like image 109
loganfsmyth Avatar answered Dec 08 '25 02:12

loganfsmyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!