Hoisting between different files

前端 未结 3 1276
被撕碎了的回忆
被撕碎了的回忆 2021-01-21 22:13

Is there a way to do functions and variable hoisting between source code present in different files? That is, something like

//Inside firstfile.js
foo === \"bar\         


        
3条回答
  •  有刺的猬
    2021-01-21 22:53

    Separately-loaded Javascript sources can all affect the global context. Thus

    window.foo = "bar";
    

    in one source file will allow another source (loaded subsequently) to check:

    if (window.foo === "bar") {
      // do something
    }
    

    This has to work, or else it would not be possible to create something like all the popular Javascript frameworks.

    The "this" keyword is only meaningful inside a function, and its value has nothing to do with the source file from which the function came (at least, nothing in any direct sense).

    edit — I guess that the interesting thing here is the Javascript interpreter behavior that (to use the term in the question) "hoists" function declarations up before other code in a block being evaluated. That also is done on a script-by-script basis when the browser is loading them. Thus, function declarations in a script block are interpreted before other code in each block, but a single

提交回复
热议问题