首页 > 解决方案 > 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?

标签: javascript

解决方案


你可以使用 || 运算符以获取回调或回退到 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));


推荐阅读