patternjavascriptCritical
Pass a JavaScript function as parameter
Viewed 0 times
functionjavascriptpassparameter
Problem
How do I pass a function as a parameter without the function executing in the "parent" function or using
I have this:
It works, but the problem is that
I could get around it using
eval()? (Since I've read that it's insecure.)I have this:
addContact(entityId, refreshContactList());It works, but the problem is that
refreshContactList fires when the function is called, rather than when it's used in the function.I could get around it using
eval(), but it's not the best practice, according to what I've read. How can I pass a function as a parameter in JavaScript?Solution
You just need to remove the parenthesis:
This then passes the function without executing it first.
Here is an example:
You can also pass anonymous functions:
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);You can also pass anonymous functions:
function addContact(id, refreshCallback) {
refreshCallback();
// You can also pass arguments if you need to
// refreshCallback(id);
}
addContact(1, () => alert('hello world'));Context
Stack Overflow Q#13286233, score: 1205
Revisions (0)
No revisions yet.