Pass a JavaScript function as parameter

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

    I suggest to put the parameters in an array, and then split them up using the .apply() function. So now we can easily pass a function with lots of parameters and execute it in a simple way.

    function addContact(parameters, refreshCallback) {
        refreshCallback.apply(this, parameters);
    }
    
    function refreshContactList(int, int, string) {
        alert(int + int);
        console.log(string);
    }
    
    addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 07:52

    To pass the function as parameter, simply remove the brackets!

    function ToBeCalled(){
      alert("I was called");
    }
    
    function iNeedParameter( paramFunc) {
       //it is a good idea to check if the parameter is actually not null
       //and that it is a function
       if (paramFunc && (typeof paramFunc == "function")) {
          paramFunc();   
       }
    }
    
    //this calls iNeedParameter and sends the other function to it
    iNeedParameter(ToBeCalled); 
    

    The idea behind this is that a function is quite similar to a variable. Instead of writing

    function ToBeCalled() { /* something */ }
    

    you might as well write

    var ToBeCalledVariable = function () { /* something */ }
    

    There are minor differences between the two, but anyway - both of them are valid ways to define a function. Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:

    anotherFunction(ToBeCalledVariable);
    
    0 讨论(0)
  • 2020-11-22 07:55

    I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :

    function foo(blabla){
        var func = new Function(blabla);
        func();
    }
    // to call it, I just pass the js function I wanted as a string in the new one...
    foo("alert('test')");
    

    And that's working like a charm ... for what I needed at least. Hope it might help some.

    0 讨论(0)
  • 2020-11-22 07:55

    Some time when you need to deal with event handler so need to pass event too as an argument , most of the modern library like react, angular might need this.

    I need to override OnSubmit function(function from third party library) with some custom validation on reactjs and I passed the function and event both like below

    ORIGINALLY

        <button className="img-submit" type="button"  onClick=
     {onSubmit}>Upload Image</button>
    

    MADE A NEW FUNCTION upload and called passed onSubmit and event as arguments

    <button className="img-submit" type="button"  onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>
    
    upload(event,fn){
      //custom codes are done here
      fn(event);
    }
    
    0 讨论(0)
  • 2020-11-22 07:56

    There is a phrase amongst JavaScript programmers: "Eval is Evil" so try to avoid it at all costs!

    In addition to Steve Fenton's answer, you can also pass functions directly.

    function addContact(entity, refreshFn) {
        refreshFn();
    }
    
    function callAddContact() {
        addContact("entity", function() { DoThis(); });
    }
    
    0 讨论(0)
提交回复
热议问题