我对 JavaScript 还很陌生。在浏览 javascript 代码时,我发现::
function Method1(sender, args) { ... }
function Method2(source, arguments) { ... }
什么时候使用(sender,args)和(source,arguments)?他们的意思是什么?
最佳答案
arguments
实际上不是JS reserved word ,否则你的Method2
不会起作用并且会抛出语法错误。
何时 arguments
用于函数的参数列表中,它只是一个常规函数参数/参数,与您的 sender
完全相同, source
和args
.
现在确实是Arguments
不能用作类名。 JavaScript 在内部使用它来创建 arguments
object (这是 Tushar 在评论中提到的)。
When control enters an execution context for function code, an arguments object is created unless (as specified in 10.5) the identifier arguments occurs as an Identifier in the function’s FormalParameterList or occurs as the Identifier of a VariableDeclaration or FunctionDeclaration contained in the function code.
在每个函数中,您都可以使用此 arguments
访问该函数调用期间传递的所有参数。类似数组的对象。它对于可能接受非预定(可能是无限)数量的参数的函数非常有用。
那么你的 Method2
会发生什么?是它使用相同的标识符“参数”,现在只分配一个参数。就好像它遮蔽了内置的 arguments
对象。
如果参数列表中没有使用它,arguments
功能 block 内将自动分配所有参数的列表。
演示:http://jsfiddle.net/5cexbrff/ (在控制台中查看结果)
关于javascript - javascript函数中不同类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844689/