Sunday, May 19, 2024
181
rated 0 times [  188] [ 7]  / answers: 1 / hits: 5842  / 11 Years ago, thu, january 30, 2014, 12:00:00

I habitually pass parameters to functions as object literals, thus....



calling:



render({
param1: 99
param2: {'a': 88, 'b': 77}
});


method:



render: function (p) {
alert( p.param1);
var data = p.param2;

etc
}


I tend to pass parameters like this in all cases nowadays - even if the function / method only accepts 1 argument. The reason is that I find this method neat and also if I wish to add another parameter at a later date it is simple to add to to the object.



I would like to know from some experienced javascript people if there is any reason why doing things in this way might be a bad idea - I do not work with other developers so am sometimes unsure if the way I do things is correct.



Thanks!


More From » parameter-passing

 Answers
4

Parameter buckets are basically a good idea. What is missing here:



render: function (p) {
alert( p.param1);
var data = p.param2;

etc
}


is, that if p.param2 is not set, you still proceed with an undefined. Buckets need to be validated with default values. There's a thread here, discussing this.



In order to have that more generic, you might do:



render: function (p) {
var myDefaults = { param1: 99
param2: {'a': 88, 'b': 77} };
$.extend(p, myDefaults);

alert( p.param1);
var data = p.param2;

etc
}


and see here for jQuery doc


[#48222] Wednesday, January 29, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;