[英]Why can argument(s) be passed to a function that has no parameter in javascript?
Today I encountered a weird decorator function that does not have any parameter but used arguments
inside its scope.今天我遇到了一个奇怪的装饰器函数,它没有任何参数,但在其作用域内使用了
arguments
。 I thought it's a mistake at first.我一开始以为是个错误。
Then I defined such a function in node:然后我在node中定义了这样一个函数:
noParameterFunction() {
console.log(arguments)
}
calling this function with argument 'a'
would give me the results below:用参数
'a'
调用这个函数会给我以下结果:
> noParameterFunction('a')
[Arguments] { '0': 'a' }
undefined
I was expecting an error in which arguments are passed to a function that takes no argument to be thrown, but I got this.我期待一个错误,其中参数被传递给一个不带参数被抛出的函数,但我得到了这个。
Can anyone explain the rationale behind this design?任何人都可以解释这种设计背后的基本原理吗? Thanks.
谢谢。
PS Declaring the function using arrow will fail to reproduce the result below. PS 使用箭头声明函数将无法重现下面的结果。
The [arguments] object contains an array of the arguments passed to the function. [arguments] 对象包含传递给函数的参数数组。
A parameter is a variable that you define at the same time you define a method and will hold the argument passed to it, an argument is the actual variable you pass to that parameter.参数是您在定义方法的同时定义的变量,并将保存传递给它的参数,参数是您传递给该参数的实际变量。 You are printing the arguments, that is, the values you pass when you call the function.
您正在打印参数,即您在调用函数时传递的值。 Since you are calling it with the argument "a", it is printed and can actually be used through the [arguments] object, so it is not an error and won't trigger an exception.
由于您使用参数“a”调用它,因此它被打印出来并且实际上可以通过 [arguments] 对象使用,因此它不是错误并且不会触发异常。
arguments
is an Array-like object accessible inside functions that contains the values of the arguments passed to that function.arguments
是一个可在函数内部访问的类数组对象,其中包含传递给该函数的参数的值。The
arguments
object is a local variable available within all non-arrow functions.arguments
对象是所有非箭头函数中可用的局部变量。
Can anyone explain the rationale behind this design?任何人都可以解释这种设计背后的基本原理吗?
The
arguments
object is useful for functions called with more arguments than they are formally declared to accept.arguments
对象对于调用的参数比正式声明接受的参数多的函数很有用。 This technique is useful for functions that can be passed a variable number of arguments.这种技术对于可以传递可变数量参数的函数很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.