Pass a JavaScript function as parameter

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

    You just need to remove the parenthesis:

    addContact(entityId, refreshContactList);
    

    This then passes the function without executing it first.

    Here is an example:

    function addContact(id, refreshCallback) {
        refreshCallback();
        // You can also pass arguments if you need to
        // refreshCallback(id);
    }
    
    function refreshContactList() {
        alert('Hello World');
    }
    
    addContact(1, refreshContactList);
    

提交回复
热议问题