Is there a way to allow "unlimited" vars for a function in JavaScript?
Example:
load(var1, var2, var3, var4, var5, etc...)
load(var1)
Is there a way to allow "unlimited" vars for a function in JavaScript? Example:
|
|||||
|
Sure, just use the
|
|||||||||||||
|
Another option is to pass in your arguments in a context object.
and use it like this
This has the advantage that you can add as many named arguments as you want, and the function can use them (or not) as it sees fit. |
|||||||||||||
|
I agree with Ken's answer as being the most dynamic and I like to take it a step further. If it's a function that you call multiple times with different arguments - I use Ken's design but then add default values:
This way, if you have many parameters but don't necessarily need to set them with each call to the function, you can simply specify the non-defaults. For the extend method, you can use jQuery's extend method (
This will merge the context object with the defaults and fill in any undefined values in your object with the defaults. |
|||||||||
|
Yes, just like this :
|
|||
|
Although I generally agree that the named arguments approach is useful and flexible (unless you care about the order, in which case arguments is easiest), I do have concerns about the cost of the mbeasley approach (using defaults and extends). This is an extreme amount of cost to take for pulling default values. First, the defaults are defined inside the function, so they are repopulated on every call. Second, you can easily read out the named values and set the defaults at the same time using ||. There is no need to create and merge yet another new object to get this information.
This is roughly the same amount of code (maybe slightly more), but should be a fraction of the runtime cost. |
|||||
|
Use the |
||||
|