You are here: irt.org | FAQ | JavaScript | Function | Q1234 [ previous next ]
Michael Djoerby writes:
The function cloneFunctionToString( _func ) can from an arbitrary function produce a string. Example:
function testwithparm( _val1, _val2 )
{
alert( 'val1=' + _val1 );
alert( "val2=" + _val2 );
}
var str = cloneFunctionToString( testwithparm );
and then later, somewhere completely different the string can be evaluated to produce a real function again.
var testwithparmCloned = eval( str );
The advantage being the complete seperation from any object references like ex. the current document object.
The implementation is a bit tricky (traps here and there) but it seem to work fine even with different ' and " in the function.
<html>
<head>
<script language="JavaScript"><!--
function testwithparm( _val1, _val2 )
{
alert( 'val1=' + _val1 );
alert( "val2=" + _val2 );
}
function testnoparm()
{
alert("Hello World!");
alert("I have no parameters!");
}
function cloneFunctionToString( _func )
{
// Find first the whole function string:
var functionString = _func.toString();
// Extract the function body:
var bodyString = functionString.substring( functionString.indexOf("{")+1, functionString.lastIndexOf("}") );
// Extract the function argument:
var functionArg = functionString.substring( functionString.indexOf("(")+1, functionString.indexOf(")") );
// Build an array containing all function arguments:
var argArray = functionArg.split(",");
// Start building the cloning string:
var retString = "new Function(";
// Add paramters to cloning string:
for ( var i = 0; i < argArray.length; i++ )
{
retString += "'" + argArray[i] + "',";
}
// Add function body to cloning string:
retString += "'" + bodyString + "')";
// The function body contains unwanted newlines, remove them:
retString = retString.replace(/\n/g," ");
return retString;
}
// Example: Function with parameters cloned:
var testwithparmCloned = eval( cloneFunctionToString( testwithparm ) );
// Example: Function without parameters cloned:
var testnoparmCloned = eval( cloneFunctionToString( testnoparm ) );
//--></script>
</head>
<body onLoad="testwithparmCloned('Hello','World'); testnoparmCloned();">
</body>
</html>