0

I am unsure why console.log(this) returns undefined in javascript files. Shouldn't it be the global object since it is not inside a function. Is it something to do with modules?

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>React App</title>
    <script src="node_modules/react/umd/react.development.js"></script>
    <script src="node_modules/react-dom/umd/react-dom.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.17.0/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div> 
    <script type="text/babel" src="./src/components/Child.js"></script>
    <script type="text/babel" src="./App.js"></script>
  </body>
</html>

App.js

console.log(this)

const App = () => <Child />

ReactDOM.render(<App />, document.getElementById('app'))

Child.js

console.log(this)

const Child = () => 
  <div>
    <h3>Child</h3>
  </div>

Both console.log(this) calls log undefined

Kashif999
  • 1
  • 5
  • 1
    It's `undefined` in strict mode without a calling context – CertainPerformance Nov 04 '20 at 21:05
  • This is not using strict mode – Kashif999 Nov 04 '20 at 21:07
  • Double check - you must be for it to be logging `undefined` – CertainPerformance Nov 04 '20 at 21:13
  • All the code being used is pasted in the question. Unless using react.development.js, react-dom.development.js or babel.min.js indirectly introduces strict mode not sure how it will be in strict mode. There are only three files in the project (Index.html, App.js and Child.js). Three external files are imported in tags. Maybe babel.min.js forces strict mode? – Kashif999 Nov 04 '20 at 21:47
  • I changed this to be a duplicate of a different question that actually answers your question. The answer is that Babel does this because it treats the file as a module by default. – loganfsmyth Nov 05 '20 at 01:44

0 Answers0