Pass a JavaScript function as parameter

前端 未结 13 1810
星月不相逢
星月不相逢 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 07:46

    The other answers do an excellent job describing what's going on, but one important "gotcha" is to make sure that whatever you pass through is indeed a reference to a function.

    For instance, if you pass through a string instead of a function you'll get an error:

    function function1(my_function_parameter){
        my_function_parameter();   
    }
    
    function function2(){
     alert('Hello world');   
    }
    
    function1(function2); //This will work
    
    function1("function2"); //This breaks!
    

    See JsFiddle

提交回复
热议问题