Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Creating a Dynamic Runtime Function

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 95
    Comment on it

    Hello readers in this tutorial we will create a dynamic runtime function. When you need to create a runtime function, in that case you do not know its structure untill the code runs. In this blog we will discuss about how to make a runtime function.


    We can use an anonymous function, to created using the Function object constructor:


     // two parameters and one function body string
     var nameOfFunction = new Function (x, y, functionBody);
     nameOfFunction(varA, varB); // two parameters are processed by function     


    Anonymous functions are those functions which is created by using the new function object constructor. They have now name given when they are created and those functions are assigned to a variable. When ever you need to call that function, you can use that variable to call function.


    Anonymous function can be parsed at runtime, which makes it inefficient for the usual reason.
    But they allow to define parameter and function body at runtime, which is helpful if you are not sure about what is the function body is to be until runtime.


    Here is the example for showing that javascript application prompts the web page readers to provide function that takes two parameters, as well as the values of those parameters, Then application use those values to run the application.


    <!DOCTYPE html>
    <html xmlns="">
     <title>Anonymous Function</title>
    window.onload=function() {
      var func = prompt("Enter function body:","");  
      var x = prompt("Enter value for x:","");  
      var y = prompt("Enter value for y:","");
      var newFun = new Function("x","y",func);  
      var result = newFun(x,y);

    In the above example if enter hello world in the two prompts, the result you will get is "Hello World".
    The variable is assigned to a function that returns value, just for a case if the dynamic function body returns a value. When the returned value is undefined that means the returned value have no value. When passing a functions as arguments or assign them to object property, then the anonymous functions are useful.


    In most of the cases literal function is preferable over a function object, because these function are passed once when the application loads.


 0 Comment(s)

Sign In

Sign up using

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: