简体   繁体   中英

Calling function with a dynamic argument type

How to call a function with different types because i want sometimes to call it with the event object and sometimes with an array or anything else than an event

const onChange = (e) => {
    if( e is Event ) { // something like this
        // do some stuff with e.target.value
    } else { // different argument type
        ...
    }
}

Calling it with event object

<input type="text" onChange={ (e) => onChange(e) } />

Calling it with an different argument type

<input type="checkbox" onChange={ (e) => {
    let newValues;
    // do some calculation
    ...
    onChange(newValues); 
}}/>
...

Well, if you do typeof e in both cases you will get object as a response because event and array are both objects in javascript.

To detect if an object is an array you have Array.isArray() .

And to detect if an object is a DOM event you could do e instanceof Event .

In reactjs you have to change it to e.nativeEvent instanceof Event

So you could do something like this:

 const a = document.getElementById('test'); const onClick = (e) => { // use (e.nativeEvent instanceof Event) in reactjs instead if(e instanceof Event) { // do some stuff with e.target.value console.log("Response: I received an event"); } else if (Array.isArray(e)) { // it's an array console.log("Response: I received an array"); } } a.addEventListener('click', onClick); console.log('Call the method passing an array'); onClick([2,3,4]); 
 <div id='test'>click</div> 

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