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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With