Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Function() constructor in javascript.

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 38
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: