4

(There is another question of similar title out there but I have a different question here.)

It's stated that in ES6, an imported module is "executed" immediately. However, say for example I have exported an object:

let Player = {
  player: null,

  init(domId, playerId, onReady) {
    window.onYouTubeIframeAPIReady = () => {
      this.onIframeReady(domId, playerId, onReady)
    }
  },

  ...
}
export default Player

Apparently the object only contains properties and methods. Then, I import it in another module:

import Player from "./player"

How can a series of name-value pairs be "executed" though? To execute the constructor of a class when it's imported makes much more sense (is a class's constructor automatically run when it's imported though? I'm also confused on that), but to "execute" an object just doesn't make much sense to me.

Also, if I import a function from another module, does the function gets immediately "evaluated" and its result produced? This also doesn't seem very right to me since a function sometimes requires arguments, which the importing module doesn't automatically provide any.

Maybe I misunderstood the meaning of the word "execute"/"evaluate" here?

Community
  • 1
  • 1
xji
  • 7,341
  • 4
  • 40
  • 61
  • 1
    when a javascript file is imported, the entire thing is literally "executed", meaning you get classes, functions and variables defined even if no code is actually run. i.e. Before the import, the Player object didn't exist. defining still requires script to be executed – Tibrogargan Sep 24 '16 at 04:25
  • @Tibrogargan I see. So if I execute the **whole** code literally then it gets defined and becomes available in the current scope. So, even if a class is imported, it's still just *defined* in the current importer module, and its constructor won't be run? – xji Sep 24 '16 at 04:31
  • @JIXiang All statements are executed. So if you call the constructor on object creation, it will be executed, then imported. – Andrew Li Sep 24 '16 at 04:33
  • 3
    There's nothing stopping an imported script from running code immediately, however most often the bulk of the work will be definitions. – Tibrogargan Sep 24 '16 at 04:34
  • Export a constructor function and then you can call the constructor with whatever arguments you want after importing and you can have it create a new object each time the constructor is called if you want. – jfriend00 Sep 24 '16 at 04:36
  • What I mean is the constructor won't be run at the instant of the import, if the imported code itself doesn't involve creating new objects using the class. But it might still be called and run after it's imported. Is that correct? – xji Sep 24 '16 at 04:52
  • What are you trying to achieve? – guest271314 Sep 24 '16 at 05:14
  • 1
    Yes, the constructor won't be run at the instant of import, but could be run at any time after that – Tibrogargan Sep 24 '16 at 05:24

0 Answers0