/ Published in: JavaScript
By not being limited to provide certain arguments/parameters in right order when calling a function, makes the function more versatile and easier to extend without breaking old code (e.g. calls to the function).
One solution is to pass an associative array holding the parameters.
Advantage: argument order is unnecessary, each argument have a label - easier to remember.
One solution is to pass an associative array holding the parameters.
Advantage: argument order is unnecessary, each argument have a label - easier to remember.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function someFunction(params) { var a = (params.a === undefined) ? "default value" : params.a /* If undefined, set default value */, b = (params.b === undefined) ? "default value" : params.b /* If undefined, set default value */, sum = a + b, myobject = {}, i, j, el = (params.el === undefined) ? document.getElementById("default") : params.el /* If undefined, set default value */, style = el.style; // do something with el and style... // function body... } // call function with associative array: someFunction({ a: 'Dette er en titel', b: 'http://www.dr.dk/OmDR/Nyt_fra_DR/Nyt_fra_DR/2008/11/25141639.htm', el: document.getElementById("result") })