[thelist] [JS] window.onload is a liar...

liorean liorean at f2o.org
Tue Mar 16 07:49:30 CST 2004


Tom Dell'Aringa wrote:
> --- liorean <liorean at f2o.org> wrote:
>>window.onload should be a function - it will trigger when the
>>document has loaded. You, however, assign it the return value of a 
>>function.
> 
> When you say it should be a function - do you mean to say
> window.onload *itself* is a function and that it triggers - or that a
> function should be *assigned* to it?

window.onload is a member of the window object. The member object should 
be of the type function. If you assign to a member, you effectively 
replace the member object with another object. It's the member object 
that should be a function.

> Second question: So doing it my original way is not assigning a
> function but assigning it a return value?

Yes. It's the same as doing

var t=BuildSelect(arr);

but with window.onload instead of var t.

On the other hand,
>>window.onload=BuildSelect;
>>
>>will assign the function itself to the onload handler. However, you
>>are losing the argument if you do thus. How to fix that?

Here, let's see if this way of thinking will help:
- There is no difference between variables on one side and functions on 
the other side. They are just names in a single namespace.
- There is no difference between members (properties and methods) on one 
side and variables on the other side. They are just names.
- A function is a value in the same way a number or a string is. You can 
pass it around as a value. However, functions have the special property 
that they can be executed.
- If a function is executed, it will return a value, the same way every 
other expression does. That value may be undefined if you aren't 
explicitly returning a value, though.

Say you have a function x. Then you can either assign the function itself:

a=x;

or you can call the function and assign it's return value:

a=x();

However, say you have a function y that calls function x. Then you can 
do the same with function y:

b=y;

or call it:

b=y();

Note that when you assign the function y, it is not executed, and thus y 
does not call x. If you on the other hand call y, y will be executed and 
in turn call x, which will be executed.

>>window.onload=function(){
>>     BuildSelect(arr);
>>}
> 
> 
> Riiight thats it! Good heavens my memory is shot. Could you explain
> the difference? I'm not quite grasping why my first version fails and
> this works. It seems both ways you assign a function to the event
> handler. I know they are different, but I can't quite wrap my fat
> head around it - and I am going to have to explain it!
> 
> Thanks as ever David!

You're welcome.
-- 
David "liorean" Andersson

ViewStyles, ViewScripts, SwitchStyles and GraphicsInfo bookmarklets:
<http://liorean.web-graphics.com/>
Hangouts:
<http://codingforums.com/> <http://yourmusicforums.com/>


More information about the thelist mailing list