Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    wac
    wac is offline
    Regular Coder wac's Avatar
    Join Date
    Sep 2002
    Location
    Cary, North Carolina, USA
    Posts
    359
    Thanks
    2
    Thanked 0 Times in 0 Posts

    passing a function as an argument

    Must one use the function constructor in order to pass a function or can the function name simply be supplied.

    eg.

    function func1(arg1) { alert 'blah '+arg1 ; }

    var func2 = new Function(arg1, "alert 'blah' +arg1;" } ;

    function func3(myfunc)
    {
    myfunc('something') ;
    }

    can I use
    func3(func1) ;

    or must I say
    func3(func2) ;
    Wayne Christian

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    You can use a function declared either through the function declaration, the function expression, or the function constructor. It's all the same to the JavaScript engine.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    Senior Coder
    Join Date
    Feb 2004
    Posts
    1,206
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I think you can do it either way (at least in IE.. if that means anything!)

    This is the code that I used to test:
    Code:
    <html>
     <head>
      <title>Untitled</title>
    
      <script>
       function blah(txt) {
        alert(txt);
       }
     
       var blee = new Function("txt", "alert(txt);");
     
       function callFn(fn, txt) {
        fn(txt);
       }
      </script>
     </head>
     <body>
    
      <script>
       callFn(blah, "blah");
       callFn(blee, "blee");
      </script>
    
     </body>
    </html>
    If someone can verify that this works in other browsers, then it looks good.

    Hope that helps,
    Sadiq.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •