Да.Ссылки на функции такие же, как и на любые другие ссылки на объекты, вы можете передать их по душе.
Вот более конкретный пример:
function foo() {
console.log("Hello from foo!");
}
function caller(f) {
// Call the given function
f();
}
function indirectCaller(f) {
// Call `caller`, who will in turn call `f`
caller(f);
}
// Do it
indirectCaller(foo); // alerts "Hello from foo!"
Вы также можете передать аргументы для foo
:
function foo(a, b) {
console.log(a + " + " + b + " = " + (a + b));
}
function caller(f, v1, v2) {
// Call the given function
f(v1, v2);
}
function indirectCaller(f, v1, v2) {
// Call `caller`, who will in turn call `f`
caller(f, v1, v2);
}
// Do it
indirectCaller(foo, 1, 2); // alerts "1 + 2 = 3"