Pass a JavaScript function as parameter

前端 未结 13 1517
星月不相逢
星月不相逢 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

    You can also use eval() to do the same thing.

    //A function to call
    function needToBeCalled(p1, p2)
    {
        alert(p1+"="+p2);
    }
    
    //A function where needToBeCalled passed as an argument with necessary params
    //Here params is comma separated string
    function callAnotherFunction(aFunction, params)
    {
        eval(aFunction + "("+params+")");
    }
    
    //A function Call
    callAnotherFunction("needToBeCalled", "10,20");
    

    That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.

提交回复
热议问题