Javascript - 将参数传递给函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4893642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - Passing arguments to function
提问by jyoseph
I've always passed arguments to a function like so:
我总是将参数传递给这样的函数:
setValue('foo','#bar')
function setValue(val,ele){
$(ele).val(val);
};
Forgive the silly example. But recently I have been working on a project that has some functions that take a lot of arguments. So I started passing the arguments through as an object (not sure if that's the correct way to put that), like so:
原谅这个愚蠢的例子。但是最近我一直在做一个项目,它有一些需要很多参数的函数。所以我开始将参数作为对象传递(不确定这是否是正确的放置方式),如下所示:
setValue({
val:'foo',
ele:'#bar'
});
And then in the function:
然后在函数中:
function setValue(options){
var value = options.val;
var element = options.ele;
$(element).val(value);
};
My question is, is there a better way to do that? Is it common practice (or okay) to call these 'options'? And do you typically need to 'unpack' (for lack of a better term) the options and set local vars inside the function? I have been doing it this way in case one of them was not defined.
我的问题是,有没有更好的方法来做到这一点?调用这些“选项”是常见的做法(或可以)吗?您是否通常需要“解包”(因为没有更好的术语)选项并在函数内设置局部变量?我一直在这样做,以防其中一个没有被定义。
I'm really looking to not create bad habits and write a bunch of code that is ugly. Any help is appreciated and + by me. Thanks.
我真的不希望养成坏习惯并编写一堆丑陋的代码。我对任何帮助表示赞赏和 +。谢谢。
采纳答案by simshaun
I do the exact same thing, except I don't declare a new variable for each option inside the function.
我做完全相同的事情,除了我没有为函数内的每个选项声明一个新变量。
I think options is a good name for it although I shorten it to opts.
我认为 options 是一个好名字,尽管我将其缩短为opts。
I always have a "default" object within the function that specify default values for each available option, even if its simply null. I use jQuery, so I can just use $.extend to merge the defaults and user-specified options like this: var opts = $.extend({}, defaults, opts);
我在函数中总是有一个“默认”对象,它为每个可用选项指定默认值,即使它只是null。我使用 jQuery,所以我可以使用 $.extend 来合并默认值和用户指定的选项,如下所示:var opts = $.extend({}, defaults, opts);
回答by Andrew Whitaker
I believe this is a great pattern. I've heard an options object like this referred to as a "builder object" in other languages (at least in the context of object creation). Here are some of the advantages:
我相信这是一个很好的模式。我听说过这样的选项对象在其他语言中被称为“构建器对象”(至少在对象创建的上下文中)。以下是一些优点:
- Users of your function don't have to worry about what order the parameters are in. This is especially helpful in cases like yours where the method takes a lot of arguments. It's easy to get those mixed up, and JavaScript will not complain!
- It's easy to make certain parameters optional (this comes in handy when writing a plugin or utility).
- 您的函数的用户不必担心参数的顺序。这在像您这样的方法需要大量参数的情况下特别有用。很容易把它们搞混,JavaScript 不会抱怨!
- 将某些参数设为可选很容易(这在编写插件或实用程序时会派上用场)。
There are some pitfalls though. Specifically, the user of your function could not specify some of the options and your code would choke (note that this could also happen with a normal JS function: the user still doesn't have to supply the correct arguments). A good way for handling this is to provide default values for parameters that are not required:
不过也有一些陷阱。具体来说,您的函数的用户无法指定某些选项并且您的代码会阻塞(请注意,这也可能发生在普通的 JS 函数中:用户仍然不必提供正确的参数)。处理这个问题的一个好方法是为不需要的参数提供默认值:
var value = options.val || 0;
var element = options.ele || {};
$(element).val(value);
You could also return from the function immediately or throw an exceptionif the correct arguments aren't supplied.
如果没有提供正确的参数,您也可以立即从函数返回或抛出异常。
A good resource for learning how to handle builder objects is to check out the source of things like jQueryUI.
学习如何处理构建器对象的一个很好的资源是查看诸如jQueryUI之类的东西的来源。
回答by Graham Conzett
I realize this question is a year old, but I think the cleanest way to pass an arbitrary number of arguments to a JavaScript function is using an array and the built in apply
method:
我意识到这个问题已经有一年了,但我认为将任意数量的参数传递给 JavaScript 函数的最干净的方法是使用数组和内置apply
方法:
fun.apply(object, [argsArray])
Where fun
is the function, object
is your scope/context in which you want the function to be executed and the argsArray
is an array of the arguments (which can hold any number of arguments to be passed.
fun
函数在哪里,object
是您希望在其中执行函数的范围/上下文,argsArray
是参数数组(可以保存任意数量的要传递的参数。
The current pitfall right now is that the arguments mustbe an array (literal or object) and not an array-like object such as {'arg' : 6, 'arg2' : "stuff"}. ECMAScript 5 will let you pass array-like objects, but it only seems to work in FireFox at the moment and not IE9 or Chrome.
当前的陷阱是参数必须是数组(文字或对象)而不是类似数组的对象,例如 {'arg' : 6, 'arg2' : "stuff"}。ECMAScript 5 可以让你传递类似数组的对象,但目前它似乎只适用于 FireFox,不适用于 IE9 或 Chrome。
回答by StuperUser
It's worth remembering that all functions have a bonus parameter called arguments
that is an object very much like a JS array (it has length
but none of the array functions) that contains all the parameters passed in.
值得记住的是,所有函数都有一个额外的参数,称为arguments
一个非常像 JS 数组(它有length
但没有数组函数)的对象,它包含传入的所有参数。
Useful if you want to pass in a range of parameters (e.g.
如果您想传入一系列参数(例如
function Sum() {
var i, sum = 0;
for (i=0; i < arguments.length; i++){
sum+=arguments[i];
}
return sum;
};
If this isn't the case and you just have a lot of parameters, use the params object as you've described.
如果不是这种情况并且您只有很多参数,请按照您的描述使用 params 对象。
回答by RichardTheKiwi
If you look at the jQuery implementation, it uses an options class to handle most of the arbitrary-number-of-parameters functions, so I think you are in good company.
如果您查看 jQuery 实现,它使用一个选项类来处理大多数任意数量的参数函数,所以我认为您是一家不错的公司。
The other way is to test for arguments.length, but that only works if your arguments are always in the same order of optionality.
另一种方法是测试arguments.length,但只有当您的参数始终处于相同的可选顺序时才有效。
回答by user113716
Nothing wrong with that practice.
这种做法没有错。
"Options" seems like as good a name as any.
“选项”似乎和任何名字一样好。
You don't need to "unpack" them, but if you'll be accessing the same item several times, it will be a little more efficient to reference them in local variables because local variable access is generally quicker than property lookups.
您不需要“解包”它们,但是如果您将多次访问同一个项目,在局部变量中引用它们会更有效一些,因为局部变量访问通常比属性查找更快。