Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hoisting between different files

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" //should return true

and

//Inside secondfile.js
function bar() {
    this.foo = "bar";
}

I guess this is not possible, as different files as parsed and executed separately and in order by most javascript engines, but I do not know for sure.

I don't know even if this is in the spec from ECMA, as the parsing of different files is not really part of the language.

like image 735
Andrea Avatar asked Feb 21 '26 01:02

Andrea


1 Answers

I originally thought this was a more interesting question than it actually appears. The answer to the question I thought this was is that each <script> element represents a separate Program, each separate Program is parsed and (crucially) executed before anything happens to the next Program, therefore the effects of hoisting can only be seen within a single Program.

For example, within a single script:

<script type="text/javasscript">
    alert(typeof foo);
    function foo() {}
</script>

... alerts "function" because the function declaration is hoisted, but splitting the two lines into separate <script> elements changes this:

<script type="text/javasscript">
    alert(typeof foo);
</script>
<script type="text/javasscript">
    function foo() {}
</script>

... alerts "undefined", because the first script is executed before the second script is even parsed.

like image 109
Tim Down Avatar answered Feb 23 '26 15:02

Tim Down



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!