如果函数只有一个参数,向函数添加可选参数的正确方法是什么?



我有一个函数,我需要在onClick操作和代码的其他部分中使用它。我想创建一个可选参数。可选参数返回一个类对象,而不是false值。

import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
.html('Click me') // Try edit it...
.on('click', test)

的回报:

{
originalEvent:[object PointerEvent],
type:"click",
isDefaultPrevented:f returnFalse {...},
target:<button class="btn btn-warning m-auto"></button>,
currentTarget:<button class="btn btn-warning m-auto"></button>,
relatedTarget:null,
timeStamp:2798.800000000745,
jQuery36007002776368131782:true,
delegateTarget:<button class="btn btn-warning m-auto"></button>,
handleObj: {...},
data:undefined
}``` 

问题是通过将函数原样传递给jQuery#on(),它将接收on传递给它的所有参数。

就像这样:

//            vvvvvvv----------vvvvvvv--- Get all arguments that `on` passes and pass them to `test`
.on('click', (...args) => test(...args))

并且,jQuery#on()确实传递了一个参数给你的函数,事件对象,所以它不会退回到使用默认值。

如果您想避免这种情况,您可以在函数周围创建一个匿名包装器,它不会将参数转发给test:

import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
.html('Click me')
//                     vv--- Pass nothing in here
.on('click', () => test())

最新更新