Jump to content

Can't Unwrap Nested Functions?


mjsulliv

Recommended Posts

I’m using a onchange method for a select element. When I code the function as a nested function:

function outerFunction(){  //  do something  selectElement.onchange = function() {  // innerFunction	   // do some more stuff  }}

it works.But if I change to what I consider a cleaner syntax (nested functions look strange to me):

function outerFunction(){	//  do something	selectElement.onchange = innerFunction();}function innerFunction(){	   // do some more stuff}

it only works the first time through the code. Any thoughts would be helpful.

Link to comment
Share on other sites

When assigning a function to an event handler (or to a variable), you don't use parenthesis:

selectElement.onchange = innerFunction;

Link to comment
Share on other sites

So this precludes passing parms?
In an event, there's only one parameter passed, you can receive it in the function. It's an event object with information about the event, like which element fired the event and what kind of event it is.I'm not sure what parameters you would want to pass to a function, usually everything you need is in the event object.
Link to comment
Share on other sites

If you want to pass parameters then you do need to use an inline or anonymous function:

selectElement.onchange = function() { innerFunction(var1, var2, var3); }

If you did that, and still wanted access to the regular event object, you would need to manually get the event object and pass that to the function also. The only function with access to the event object is the event handler (the anonymous function in this case), so that function would need to get the event object and pass it along to the other function.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...