Topic: Running a function by name? (Page 1 of 1) Pages that link to <a href="http://ozoneasylum.com/backlink?for=27758" title="Pages that link to Topic: Running a function by name? (Page 1 of 1)" rel="nofollow" >Topic: Running a function by name? <span class="small">(Page 1 of 1)</span>\

 
H][RO
Bipolar (III) Inmate

From: Australia
Insane since: Oct 2002

IP logged posted posted 04-09-2006 18:20 Edit Quote

I'm sure i've done this before but for the life of me i can't find any reference to it.

Basically i want to run a function from within another function, when all i have is the name of the function that i want to run stored as a string.

so..

code:
function f1(f2Name)
{
        f2Name();
}


f1('f2')

function f2()
{
      alert('blah')
}




I actually did have it working somehow through a few functions, but not anymore - not sure what I did...

H][RO
Bipolar (III) Inmate

From: Australia
Insane since: Oct 2002

IP logged posted posted 04-09-2006 18:30 Edit Quote

Argg... nevermind - was putting brackets in wrong places... think i should go sleep some

poi
Paranoid (IV) Inmate

From: Norway
Insane since: Jun 2002

IP logged posted posted 04-09-2006 18:39 Edit Quote

How you wrote your f1() function implies that you pass the handle of a function, hence you should do:

code:
f1( f2 );

But for what you want, your f1() function should look like:

code:
function f1( functionName )
{
	var	theFunction=window[functionName];
	if( typeof(theFunction)=='function')
		return theFunction();

	//	fallback
	return null;
}

Hope that helps,

H][RO
Bipolar (III) Inmate

From: Australia
Insane since: Oct 2002

IP logged posted posted 04-09-2006 18:46 Edit Quote

Cheers, it does. What i did above would have worked if i left the quotes off f1('f2') - should be f1(f2) - then its the same as what you did, without the step declaring the function variable.

I forgot functions are objects too!



Post Reply
 
Your User Name:
Your Password:
Login Options: Remember Me On This Computer
 
Your Text:
Loading...
Options: Show Signature
Enable Slimies
Enable Linkwords

« BackwardsOnwards »

Show Forum Drop Down Menu