0

Consider this code:

<script>var foo = 'bar';</script>
<div id='isolated'>
    <script>console.log(foo)</script>
</div>

This will return 'bar' to the console. However I'd like for foo and any other variables declared outside #isolated to be undefined from within it.

How can this be achieved? A cross-browser, lightweight and native solution would be preferable.

kjaos
  • 1
  • 1

3 Answers3

3

That's not how JavaScript works. It doesn't scope itself because of a HTML element block.

You're declaring foo at the global scope, simply declare it in the scope that it would only be used when needed. Using ES6 (Harmony), using let instead of var (proposed, not fully supported) to declare a variable proposes a block level variable instead of a global scoped variable.

As it stands however, JavaScript has no idea foo is being logged inside the isolated div unless you use some logic.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
1

Try wrapping the code in between the first <script></script> tag in a function.

<script>(function fn(){var foo = 'bar';})();</script>
<div id='isolated'>
    <script>console.log(foo);</script>
</div>

This will cause whatever variables you declare to live within the context of this function. They will not be accessible outside this function.

Danny Delott
  • 6,756
  • 3
  • 33
  • 57
  • 1
    This will work, however, in the context of the question, `foo` is no longer accessible anywhere, instead of just inside the isolated div. – Sterling Archer May 29 '15 at 16:28
0

If you load your isolated code in an iframe and host the code at a different domain the scopes will be separated. You can then pass messages back and forth between the parent and the iframe via the cross-document messaging services (https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)

jsleuth
  • 638
  • 4
  • 9