Working in JS for some time now, I noticed a common feature with some JS libraries (eg. jQuery, momentJS, Vue). They usually expose single function that can accept different parameters, both in terms of parameter type and in terms of number of parameters.
For example, let's say there is a foo
function exposed by fooLib
. I can use this same function in many ways such as:
import { foo } from './fooLib'
let a = foo('test') // pass string
let b = foo({ }) // pass object
let c = foo([]) // pass array
let d = foo('test', { }) // pass multiple parameters of different type
I've never written a JS library myself but sometimes I feel like it may be useful to create function like this in my app, although I am not aware what are the best practices in that case. I tried a few times to create something like this on the small scale by checking parameter types, but the code quickly got complex and unreadable.
So how is this accomplished in general? Are there some JS patterns for this type of programming?
Aucun commentaire:
Enregistrer un commentaire