简体   繁体   中英

Javascript callback function as a optional parameter for a function

I have a javascript function which takes two arguments. First one is necessary and the second one is optional. The second argument is a callback function. How do I provide callback function as a default argument. The code that I wrote had errors. The code that I tried:

function doSomething(count,() => {}) {
//code
}

You can use default value for function parameter like below way.

function doSomething(count, fn = (() => {})) {
  //code
  //here fn is reference to the second parameter
}

Below is an example.

 function doSomething(count,fn = (() => {})) { console.log(fn()) } doSomething(1, () => {return 2})

you can use call methods for this scenario

function doSomeThing(param1, fn) {

// you should callback function
(fn ? fn : yourCustomeFunction).call(this)

}



Any argument not passed in to a function has the value of undefined . Just check to see if the callback is defined:

function doSomething(count,callback) {
    // code
    if (callback !== undefined) {
        callback()
    }
}

To be safer, you can also check if callback is a function:

function doSomething(count,callback) {
    // code
    if (typeof callback === 'function') {
        callback()
    }
}
function doSomething(count,callback) {
    // code
    if (!!callback) {
        callback()
    }
}

Check whether the second argument is there or not.

To provide callback as default argument, you can try:

const doSomeAction = (callback = Function()) => {
  // write code here
  callback();
}

doSomeAction();

However, there are lot of other ways of doing, I prefer this approach as it's cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM