0

this is the main React component:

class App extends Component {
  componentDidMount() {
    console.log(this)
    init()
  }
  // react render
  render() {
    return (
      <div ref={ref => (this.mount = ref)} />
    )
  }
}

export default App;

And in anotther file, i have this function which i import in App.js:

var init = () => {
    console.log(this)
    // Initiates the entire env

    // Initiate clock
    this.clock = new THREE.Clock()
    ...
    // Add event listener in case window resizes
    window.addEventListener('resize', this.onWindowResize, false)
    ...

}

It is to my understanding that an arrow function does not have its own scope/this so that it gets the this of the enclosing scope. Why does it not work in this example? The first print, in the App component prints right and the next print gets undefined.

This is how the two prints look like: enter image description here

Mike
  • 400
  • 5
  • 21
  • What is the context where `init` is? – VLAZ Apr 22 '20 at 06:16
  • *And in anotther file* Since `this` is inherited lexically, the scope in which `init` is declared in that other file must not have a calling context either. `console.log(this); var init = () => {` will show you `undefined` as well. – CertainPerformance Apr 22 '20 at 06:18
  • @VLAZ it's just another file, *main.js* where i declared a bunch of functions so that i won't clogg App.js file. I export them with *export { init, animate };* and import them like this *import { init, animate } from './js/main'* – Mike Apr 22 '20 at 06:19
  • @Mike if it's another file, then the context is different. If it's different, then it's not `App`. As you yourself said - the arrow function would use the enclosing context and in the latter case, there is none. – VLAZ Apr 22 '20 at 06:20
  • @VLAZ, ok, and is there any import method to achieve this result without having to put them all in the same file? Coming from python this is very confusing – Mike Apr 22 '20 at 06:22
  • `import` doesn't alter the context. You can use normal functions that will dynamically get the `this` value when executed or even set it via `.bind`, `.call` or `.apply`. I'm not clear what your goal is but these are the normal mechanisms. Given that the code is not part of the `App` class, I'd even say you should probably just not use `this` but do something like `ley myApp = new App()` and then use `myApp` (or whatever you want to call the variable) instead of `this`. – VLAZ Apr 22 '20 at 06:26

0 Answers0