将javascript方法参数作为对象文字传递 [英] passing javascript method params as object literal
问题描述
我习惯性地将参数作为对象字面量传递给函数,因此....
I habitually pass parameters to functions as object literals, thus....
调用:
render({
param1: 99
param2: {'a': 88, 'b': 77}
});
方法:
render: function (p) {
alert( p.param1);
var data = p.param2;
etc
}
我现在倾向于在所有情况下都传递这样的参数 - 即使函数/方法只接受 1 个参数.原因是我觉得这个方法很简洁,而且如果我想在以后添加另一个参数,添加到对象中也很简单.
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.
我想从一些有经验的 javascript 人员那里知道是否有任何理由为什么以这种方式做事可能是个坏主意 - 我不与其他开发人员一起工作,所以有时不确定我做事的方式是否正确.
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.
谢谢!
推荐答案
参数桶基本上是一个好主意.这里缺少什么:
Parameter buckets are basically a good idea. What is missing here:
render: function (p) {
alert( p.param1);
var data = p.param2;
etc
}
是,如果 p.param2
未设置,您仍然继续使用 undefined
.需要使用默认值验证存储桶.这里有一个讨论这个问题的线程.
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
}
并查看此处了解 jQuery 文档
and see here for jQuery doc
这篇关于将javascript方法参数作为对象文字传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!