passing javascript method params as object literal [closed]

末鹿安然 提交于 2021-02-19 07:20:59

问题


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!


回答1:


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




回答2:


In my oppinion its a matter of taste how to pass your parameters. I think you should validate your object literal parameters or provide default values with something like jQuery.extend:

var myParams = jQuery.extend({
  param1: 99 // default value for param1
  param2: { a: 10, b: 10 } // default value for param2
}, params);

When it comes to rendering, like in your example performance might be an argument for one option. I did a quick test http://jsperf.com/obj-literal-params. In my case (Chrome 32) using object literal parameters with jQuery.extend is about 80% slower than using normal function parameters. But that might be an insignificant performance loss when related to the rest of your rendering function.

My conclusing is: Use what you like most and what makes the code more readabl




回答3:


No arguments... :)

I started like you .. but i noticed that most of my functions are based on ajax or events or based on a plugin . In that case i never use arguments else i have to use bind and lose the native Event.So i try to get everything i need from globals or elements.

(function(){
var myGlobals={};
function ajax(){
 //....
};
function handleAjax(e){
 myGlobals.currentAjaxResponse=JSON.parse(this.response);
}
function handleClick(e){
 myGlobals.elements
 myGlobals.currentAjaxResponse
 myGlobals.data
 e.target
}
function handleLoad(e){
 myGlobals.elements=document.getElemntsByClassName('buttons');
 myGlobals.elements[0].addEventListener('click',calculateXY,false);
 myGlobals.data={x:1,y:2}
 window.removeEventListener('load',handleLoad,false);
}
function calculateXY(){
 myGlobals.data.x+
 myGlobals.data.y+
 (myGlobals.elements[0].dataset['num']*1)+
 (e.target.dataset['num']*1)+
 myGlobals.currentAjaxResponse.key
}
window.addEventListener('load',handleLoad,false);
})()

only if i use some basic utilies to convert stuff i use:

function(argument){return result}

and most of the time i need just one argument.

And as you say if i need a objet i pass an object.




回答4:


This pattern can surely be useful, but I tend not to use it unless it's actually justified - as it is considering jQuery.extend(), or a data binding (link) for example.

Maybe I'm not fully qualified to talk about that but, I'm afraid that it's likely to lead to bad habits in terms of software architecture. I mean, ignoring the function's signature, you're creating some sort of "catch-all" function, easily mutable, but poorly characterized. Is it really a drawback? This question has probably been debated already, and I believe that it's worth thinking about.

It's also worth noting that this pattern implicitely requires the creation of an object. Beyond the fact that it might have a negative impact on performances, this coding style can be harder to understand for people who are not familiar with it.



来源:https://stackoverflow.com/questions/21453464/passing-javascript-method-params-as-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!