関数内でのthisはモードで違う

メソッドでもアロー関数でもない関数内のthisは下記の点でブラウザもNode.jsも同じ。


    ブラウザで関数内のthis

    <!DOCTYPE html>
    <html lang="ja">
    <head>
      <meta charset="UTF-8">
      <title>関数内のthis</title>
      <script>
        // モードによらず、
        // ブラウザのトップレベルのthisはグローバルオブジェクト。
        console.log(this === window) // true
    
        strictモード() // 推奨
        ゆるいモード()
        function strictモード(){
          'use strict'
          console.log(this === undefined) // true
        }
        function ゆるいモード(){
          // ゆるいと関数内thisはグローバルオブジェクト。
          console.log(this === window) // true
        }
      </script>
    </head>
    <body>
    </body>
    </html>
    

    Node.jsで関数内のthis

    #!/usr/bin/env node
    
    // モードによらず、
    // Node.jsのトップレベルのthisはグローバルオブジェクトではない。
    console.log(console === global.console, this !== global) // true true
    console.log(this === module.exports) // true
    
    strictモード()
    ゆるいモード()
    
    function strictモード() {
      'use strict'
      console.log(this === undefined) // true
    }
    
    function ゆるいモード() {
      // ゆるいと関数内thisはグローバルオブジェクト。
      console.log(this === global) // true
    }