javascript 如果我调用的 JS 方法的参数多于定义接受的参数,会发生什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12694031/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:53:16  来源:igfitidea点击:

What happens if I call a JS method with more parameters than it is defined to accept?

javascriptfunctionargumentsattachevent

提问by wwaawaw

I'd like to know both for regular all-in-the-family JS developer(me)-defined functions, as well as predefined DOM methods. Like what happens if I try to call IE's attachEventwith the signature of the WHATWG's addEventListener? For instance,

我想知道常规的全系列 JS 开发人员(我)定义的函数,以及预定义的 DOM 方法。就像如果我尝试attachEvent使用 WHATWG 的签名调用 IE 会发生什么addEventListener?例如,

elem.attachEvent('onbillgates\'mom', function(e){ this.mount(); }, false);

elem.attachEvent('onbillgates\'mom', function(e){ this.mount(); }, false);

Specifically, note the false. Will that trip anything up, even though the attachEventmethod's signature only calls for two arguments?

具体来说,请注意false. 即使attachEvent方法的签名只调用两个参数,那会不会有什么问题?

Thanks.

谢谢。

function foo(FirstOf2, SecondOf2) {
  console.log(FirstOf2 + SecondOf2);
}

foo(1, 2, true);

回答by Prinzhorn

JavaScript doesn't have the concept of a fixed parameter list. For your own functions you can always specify as many parameters as you want and pass in as many as you want which ever type you want.

JavaScript 没有固定参数列表的概念。对于您自己的函数,您始终可以指定任意数量的参数,并根据需要传入任意类型的参数。

For built-in functions, which correlate to native code, it depends.

对于与本机代码相关的内置函数,它取决于.

You asked on what it depends:

你问它取决于什么:

Let's look at the ECMA-262

我们来看看ECMA-262

Section 15 about built-in(not to confuse with host) functions in general

第 15 节关于内置(不要与主机混淆)函数的一般情况

Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given fewer arguments than the function is specified to require, the function or constructor shall behave exactly as if it had been given sufficient additional arguments, each such argument being the undefined value.

除非在对特定函数的描述中另有规定,如果本节中描述的函数或构造函数被赋予的参数少于指定函数所需的参数,则该函数或构造函数的行为应完全像它已被赋予足够的附加参数一样,每个这样的参数是未定义的值。

Alright. If I pass in less arguments than needed, it dependson the spec of the function itself (scroll down section 15 to find the spec for each built-in function).

好吧。如果我传入的参数比需要的少,这取决于函数本身的规范(向下滚动第 15 节以找到每个内置函数的规范)。

Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function. However, an implementation may define implementation specific behaviour relating to such arguments as long as the behaviour is not the throwing of a TypeError exception that is predicated simply on the presence of an extra argument.

除非在特定函数的描述中另有说明,如果本子句中描述的函数或构造函数被赋予的参数多于指定的函数允许的参数,则调用会评估额外的参数,然后函数将其忽略。然而,一个实现可以定义与这些参数相关的实现特定行为,只要该行为不是简单地基于额外参数的存在而引发的 TypeError 异常。

Passing in too many arguments should never raise a TypeError. But still it may raise other errors. Again, it dependson the function you talk about.

传入太多参数不应该引发 TypeError。但它仍然可能引发其他错误。同样,这取决于您谈论的功能。

You were talking explicitly about the DOM and not about built-in functions. To be honest I can't find the corresponding parts of the spec. The ECMA spec is so much easier to read then the w3 website.

你在明确地谈论 DOM 而不是内置函数。老实说,我找不到规范的相应部分。ECMA 规范比 w3 网站更容易阅读。

回答by Diogo Schneider

Won't hurt. You can even call a function with less parameters than it takes, as long as the function code is ok with a few undefined values.

不会痛。你甚至可以调用一个参数少于它需要的函数,只要函数代码有几个未定义的值就可以了。

回答by GalAbra

I came across this important, however old, question; and I hope it'll be beneficial for future generations to share my experiments with it:

我遇到了这个重要但古老的问题;我希望与它分享我的实验对后代有益:

  1. One can use the argumentsobject in order to access a function's arguments, regardless of the amount of arguments in the function's signature.
    It's worth mentioning that this doesn't apply to arrow functions:
  1. arguments无论函数签名中的参数数量如何,都可以使用该对象来访问函数的参数。
    值得一提的是,这不适用于箭头函数:

function singleArg(x) {
  console.log(arguments);
}

singleArg(1, 2); // Called with 2 arguments
singleArg();     // Called with 0 arguments

// Results in an error, as 'arguments' isn't defined for arrow functions
((arg) => console.log(arguments))(1);

  1. It's stated in the documentationthat argumentsisn't exactlyan Array:

    “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach() and map().

    Hence the following code results in an error:

  1. 这是在说文件arguments准确Array

    “类数组”意味着参数具有长度属性和从零开始索引的属性,但它没有 Array 的内置方法,如 forEach() 和 map()。

    因此,以下代码会导致错误:

(function singleArg(x) {
  console.log(arguments); // This line works
  arguments.foreach(x => console.log(x)); // This causes an error
})(1, 2);

  1. Upon calling a function with less arguments than in its signature, they're assigned undefined:
  1. 在调用参数少于其签名的函数时,它们被分配undefined

(function twoArgs(a, b) {
  console.log(`a: ${a}\nb: ${b}`);
})(1);

回答by Jordan Denison

I don't think it will mess anything up unless you are explicitly dealing with the implicit arguments array. Why are you doing this though?

我认为除非您明确处理隐式参数数组,否则它不会搞砸任何事情。你为什么要这样做?

回答by Chase

Try taking a look at this postand perhaps this one.

试着看看这篇文章,也许还有这个

From MDN:

来自MDN

The argumentsobject is a local variable available within all functions; argumentsas a property of Function can no longer be used.

You can refer to a function's argumentswithin the function by using the argumentsobject. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.

You can use the argumentsobject if you call a function with more argumentsthan it is formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments.

arguments对象是所有函数可用的局部变量;arguments作为 Function 的属性不能再使用。

您可以arguments通过使用arguments对象来引用函数内的函数。此对象包含传递给函数的每个参数的条目,第一个条目的索引从 0 开始。

arguments如果您调用的函数arguments超过正式声明接受的数量,则可以使用该对象 。这种技术对于可以传递可变数量参数的函数很有用。

function myConcat(separator) {
  var result = "";

  // iterate through non-separator arguments
  for (var i = 1; i < arguments.length; i++) {
    result += arguments[i] + separator;
  }

  return result;
}