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

问题描述

我有一个函数,我需要在 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
}``` 

标签: javascriptecmascript-6

解决方案


问题是通过将函数按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())

推荐阅读