Pass a JavaScript function as parameter

前端 未结 13 1542
星月不相逢
星月不相逢 2020-11-22 07:06

How do I pass a function as a parameter without the function executing in the \"parent\" function or using eval()? (Since I\'ve read that it\'s insecure.)

13条回答
  •  失恋的感觉
    2020-11-22 08:04

    If you want to pass a function, just reference it by name without the parentheses:

    function foo(x) {
        alert(x);
    }
    function bar(func) {
        func("Hello World!");
    }
    
    //alerts "Hello World!"
    bar(foo);
    

    But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:

    function foo(x) {
       alert(x);
    }
    function bar(func) {
       func();
    }
    
    //alerts "Hello World!" (from within bar AFTER being passed)
    bar(function(){ foo("Hello World!") });
    

    If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:

    function eat(food1, food2)
    {
        alert("I like to eat " + food1 + " and " + food2 );
    }
    function myFunc(callback, args)
    {
        //do stuff
        //...
        //execute callback when finished
        callback.apply(this, args);
    }
    
    //alerts "I like to eat pickles and peanut butter"
    myFunc(eat, ["pickles", "peanut butter"]); 
    

提交回复
热议问题