You can use function constructor along with new keyword when you want to define your function dynamically. Function constructor accepts any number of string arguments.
This is the syntax for it:
var variablename = new Function(Arg1, Arg2..., "Function Body");
The last argument it accepts is the function body that can contain javascript statements.
You can consider this simple example for your help:-
<html>
<head>
<script type="text/javascript">
var samplefunc = new Function("a", "b", "return a+b;");
function samplefunc1(){
var result;
result = samplefunc(10,20);
document.write ( result );
}
</script>
</head>
<body>
<p>Click me</p>
<form>
<input type="button" onclick="samplefunc1()" value="Execute">
</form>
</body>
</html>
Functions created with the Function constructor are always created in the global scope. Creating functions through contructors is a bad practice because each method has to be created every time the constructor function runs. Also it takes more memory and processing time. You can use prototype approach as it is more efficient.
0 Comment(s)