Rahul Iyer
Rahul Iyer

Reputation: 21025

Will global vars always be created before calling javascript functions?

Say I have the following:

<script>

var foo = {myFunc:function(){..some func}};

window.addEventListener('load',foo.myFunc(),false);

var bar = 'some var';

</script>

Will window.addEventListener always be able to set foo.myFunc() as a function to call on the load event? Is there any possibility that foo will be undefined when setting the event listener? When are foo and bar created, and when are they useable?

I am targeting only Safari 5.0+

Upvotes: 1

Views: 40

Answers (2)

jfriend00
jfriend00

Reputation: 707766

Variable definitions are "hoisted" to the top of a given scope so no matter where a variable is declared, it will exist before any code runs in that particular scope.

Variable assignments are executed sequentially as they are encountered in the javascript file.

So, foo will exist, but won't have its value until the assignment statement runs.


Also, your code should be this (remove the parens after myFunc):

window.addEventListener('load', foo.myFunc, false);

When you include the parens, the function is called immediately and its return value is passed. If you want to just pass a reference to the function so addEventListener() can call it later, then you need to not include the parens.

Upvotes: 1

user229044
user229044

Reputation: 239402

Yes, both foo and bar will be defined when your event handler executes.

Generally JavaScript executes synchronously, line by line. It starts at the top, and works downwards. However, this is a special case, as you're talking about variable declaration. In the case of variable and function declaration, "hoisting" occurs. Functionally what's happening is you're written this:

var foo, bar;

foo = ...;

window.addEventListener(...);

var bar = ...;

So, while foo is obviously guaranteed to be defined, so is bar. Both variables will be closed over by the function, and available when it executes.

Upvotes: 1

Related Questions