[英]What's the correct way to pass parameters to JavaScript or jQuery function?
Like this example: 像这个例子:
var variable = '';
function myFunction(param){
variable = param;
alert(variable);
}
or like this: 或像这样:
function myFunction(param){
alert(param);
}
The only reason to do it the way you show in your first example is if you NEED to store the parameter persistently in a way that will survive from one invocation of the function to another. 按照第一个示例中显示的方式执行此操作的唯一原因是,您是否需要以一种可以从一次调用该函数到另一次调用生存的方式持久存储该参数。 If you don't need that, then the second way is much, much cleaner and doesn't introduce unnecessary variables and doesn't pollute the higher scope. 如果您不需要它,那么第二种方法会更清洁得多,并且不会引入不必要的变量,也不会污染更大的范围。
I should add that arguments to functions work just like local variables. 我应该在函数中添加参数,就像局部变量一样。 There is no reason to assign them to other variables just to use them. 没有理由仅将它们分配给其他变量。 You can use the argument variable directly just fine. 您可以直接使用参数变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.