Pass a JavaScript function as parameter

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

提交回复
热议问题