我对javascript开发有了更多的了解,并希望确保我遵循的是流行的惯例。目前,我有一个库,它由函数组成,可以传递一个可操作的模型,也可以传递多个模型。
考虑到一些javascript库非常流行的气候,我很好奇;我会通过实现我的“单项或列表”需求、枚举参数变量或允许其中一个参数成为数组来达到“事实上的标准”吗?
场景1:参数枚举
// passing a single entity to my function
sendMail( email, recipient1 );
// passing multiple entities to my function
sendMail( email, recipient1, recipient2 );场景2:实体参数要么是单个实例,要么是数组
// pass a single entity
sendMail( email, recipient1 );
// passing multiple entities
sendMail( email, [recipient1, recipient2] );我已经看到了使用“场景2”的jQuery领域,但是我仍然想问--哪种方法最流行,为什么?
谢谢
编辑
有几个注释遵循同样的思路,使用一个参数对象--类似于“场景2”--但我认为它引入了不必要的复杂性--元素不需要命名,因为它们只是一个可变长度的列表。我想我应该在这里补充一下,以防我的问题不够清楚。
编辑
我在jQuery1-7.js中看到了这样的代码。
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
}编辑
经过与JP的讨论,我想到了这个--我并不是说这是正确的选择,但它非常灵活.
lastArgumentAsParams: function()
{
var callerArgs = jQuery.makeArray(this.lastArgumentAsParams.caller.arguments);
// return empty set if caller has no arguments
if ( callerArgs.length == 0 )
return [];
callerArgs.splice(0, callerArgs.length - 1)
// remove all but the last argument
if ( callerArgs.length == 1 && jQuery.isArray(callerArgs[0]))
return callerArgs[0];
else
return callerArgs;
}如果您在任何函数的开头调用此函数--它将把调用方中的最后一个arg视为“可变长度参数”--支持任何约定。
例如,我可以这样使用它
function sendEmail( body, recipients )
{
recipients = lastArgumentAsParams();
// foreach( recipient in recipients )...
}现在,我可以通过以下任何一种方式调用'sendEmail‘,它将按预期工作。
sendEmail('hello world', "bill@microsoft.com" );
sendEmail('hello world', "bill@microsoft.com", "steve@apple.com" );
sendEmail('hello world', ["bill@microsoft.com", "steve@apple.com"] );发布于 2012-03-06 20:32:52
我个人更喜欢使用对象文本作为参数来支持命名的params,如下所示:
var myfunc = function(params){ //same as: function myfunc(params){....
alert(params.firstName);
alert(params.lastName);
};
myfunc({firstName: 'JP', lastName: 'Richardson'});我认为它使代码非常可读性强,顺序也不重要。
或
还可以访问arguments对象。注意,它不是数组,但它是“数组一样的”。你可以在这里读到:http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/
编辑:
你好像有点误会。您正在使用短语“参数对象”,并认为它与对象字面符号相同。他们不是。
arguments对象允许您这样做:
function myfunc(){
alert(arguments[0]); //JP
alert(arguments[1]); //Richardson
}
myfunc('JP', 'Richardson');这有用吗?
发布于 2012-03-06 20:33:35
另一种常见的方法是将对象文字用作变量:
myFunction(true, {option: value, option2: value});我个人更喜欢这个方法,因为它更冗长,而且对于javascript松散类型,它为您提供了更好的提示,说明了这个变量是什么,并且忽略了顺序。
Backbone.js将此作为首选方法。
https://stackoverflow.com/questions/9591318
复制相似问题