By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,818 Members | 2,121 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,818 IT Pros & Developers. It's quick & easy.

var foo = 10; vs. window.foo = 10;

P: n/a
Hi,

I've wondered for a what the differences between the following.
<script type="text/javascript">
var foo = 10;
</script>

<script type="text/javascript">
window.foo = 10;
</script>

For one, I think I can do

delete window.foo;

The reason I ask is avoiding garbage collection. If I have an event
handler function for onload that declares some global object that I
want to persist I would like to avoid doing this in the head element.

<script type="text/javascript">
var foo;
function handleLoad(e) {
foo = {bar: 45};
};
</script>

I would rather have just the following if it will serve my needs as it
seems more self contained

<script type="text/javascript">
function handleLoad(e) {
window.foo = {bar: 45};
};
</script>

Thank you,
Peter

Sep 8 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
We prefer the declaring of a global varible outside a function so it's
easier to understand and read. However, remeber that for self
containment reasons use of global varibles should be minimized.
pe**********@gmail.com wrote:
Hi,

I've wondered for a what the differences between the following.
<script type="text/javascript">
var foo = 10;
</script>

<script type="text/javascript">
window.foo = 10;
</script>

For one, I think I can do

delete window.foo;

The reason I ask is avoiding garbage collection. If I have an event
handler function for onload that declares some global object that I
want to persist I would like to avoid doing this in the head element.

<script type="text/javascript">
var foo;
function handleLoad(e) {
foo = {bar: 45};
};
</script>

I would rather have just the following if it will serve my needs as it
seems more self contained

<script type="text/javascript">
function handleLoad(e) {
window.foo = {bar: 45};
};
</script>

Thank you,
Peter
Sep 9 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.