...

View Full Version : How the heck does this function work?!



Ahlahn
07-31-2011, 04:47 AM
Hey guys,

I'm beginning to learn javascript, and I've come across functions like the one below in many scripts. I just don't understand the purpose of the parameter! Nothing is being passed into the function when it's being called- so what's the point of specifying an argument???




function doSomething(e) {
if (!e) var e = window.event;
alert(e.type);
}



Why not:



function doSomething() {
var e = window.event;
alert(e.type);
}

rnd me
07-31-2011, 06:02 AM
what you have is a cross-browser event handler.

something is being passed if that function gets bound as an event.

it's the event object that is passed. in older IEs, the same object (well about the same) is not passed, but is available at window.event.

Old Pedant
07-31-2011, 06:12 AM
In other words, that code is kind of equivalent to doing this:


function doSomething(e) {
if ( this_is_an_older_MSIE_browser ) { e = window.event; } else { /* it's not IE or it's modern IE */ }
alert(e.type);
}

bullant
07-31-2011, 09:38 AM
Nothing is being passed into the function when it's being called...

Not quite correct.

The event object (http://www.javascriptkit.com/jsref/event.shtml) is being passed to the function.

rnd me
07-31-2011, 09:59 AM
The event object (http://www.javascriptkit.com/jsref/event.shtml) is being passed to the function.

hey, that's what i said:


it's the event object that is passed.

bullant
07-31-2011, 11:36 AM
and I included a link to more information.

If you have an issue with my post, report it as fluff to the moderators. If they agree with you they have the option to delete it. If they don't, I guess it will stay :)

rnd me
07-31-2011, 10:55 PM
and I included a link to more information.

If you have an issue with my post, report it as fluff to the moderators. If they agree with you they have the option to delete it. If they don't, I guess it will stay :)

lol. if you really want to be a johnny-come-lately copycat, more thread counts to you, but some find it irksome. i guess that's how you got that many posts since feb...

Ahlahn
08-01-2011, 02:02 AM
I see. Since some browsers like IE passes the event object explicitly to the calling function, we need a parameter in place to check for that. Why is the DOM so complicated? Haha.

Thank you all for you answers. Also, the link was very helpful, so thanks to Bullant for providing an extra source of information.

bullant
08-01-2011, 02:03 AM
Thank you all for you answers. Also, the link was very helpful, so thanks to Bullant for providing an extra source of information.

You're welcome :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum