简体   繁体   English

将参数传递给JavaScript或jQuery函数的正确方法是什么?

[英]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.

相关问题 在JavaScript中传递参数以正常运行的正确方法是什么? - What is the correct way to pass parameters to function in JavaScript? 调用JavaScript函数的正确方法是什么? - What's the correct way to call JavaScript Function? 销毁javascript函数的正确方法是什么? - what's the correct way to destroy a javascript function? 在javascript或jquery中,运行函数名称和参数位于json对象中的函数的最佳方法是什么? - In javascript or jquery, what's the best way of running a function whose function name and parameters come in a json object? 将“ this”传递给JavaScript的正确方法 - Correct way to pass 'this' to function in javascript 将参数传递给ajax的正确方法是什么 - What is correct way to pass parameters to ajax 在javascript中测试对象是否是jQuery对象的正确/正确方法是什么? - What's the correct/proper way to test if an object is a jQuery object in javascript? 处理 Javascript 中的可选 && 动态 function 参数的最佳方法是什么? - What's the best way of dealing with optional && dynamic function parameters in Javascript? 将这个数据库结果传递给javascript函数的正确方法是什么? - What's the right way to pass this database result into a javascript function? 在 React 中将 function 作为 Prop 传递的正确方法是什么 - What is the correct way to pass a function as a Prop in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM