javascript - One-liner to call a function if it's defined, else call another function
问题描述
I want to call a callback
function if one was provided by the user, or default to a default defaultCallback
function.
I've done it as follows:
function defaultCallback(x) {
console.log('default callback ' + x)
}
function test(callback) {
let x = 'x'
if (callback) {
callback(x)
} else {
defaultCallback(x)
}
}
I feel there should be a more concise way of doing this?
解决方案
你可以使用 || 运算符以获取回调或回退到 defaultCallback。
function test(callback) {
(callback || defaultCallback)('x')
}
这是一个测试片段,您可以使用它在控制台中查看结果。
function defaultCallback(x) { console.log('Used default ' + x); }
function test(callback) {
(callback || defaultCallback)('x')
}
test(undefined);
test((y) => console.log('Used func ' + y));
推荐阅读
- swift - 使我的 ViewController 符合 NSDraggingDestination 协议
- java - 带有spring boot JPA Postresql的data.sql未加载
- c++ - 使用 `std::error_code` 的最佳实践
- python - 拆分列表并保留python中的空格
- c# - 通过 Hangfire 在 Azure 中无法 HttpWebRequest
- python-3.x - 计算列表中所有字符串元素的多次出现?
- r - 调整 showModal 在 Shiny 上显示的图像
- android-recyclerview - 在回收站视图上配置搜索视图
- sql-server - bcp 在 CSV 输出中添加额外字符
- r - 在 R lavaan 中使用 getCov 和一个实际的大相关矩阵