【问题标题】:Why is function.apply.length 2 in JavaScript?为什么 JavaScript 中的 function.apply.length 为 2?
【发布时间】:2025-12-09 21:50:02
【问题描述】:

当我在控制台上运行这段代码时:

(function test(){
   console.log(function(){}.apply.length);
})();

输出为:2

我读到了Function length。我了解 MDN 上的函数长度部分。但我不明白这一点。函数中没有参数。为什么输出是 2?

【问题讨论】:

  • 感谢@jenny 编辑

标签: javascript function apply


【解决方案1】:

这是因为您要的是 Function.prototype.apply.length,它的 thisArgargArray2

19.2.3.1Function.prototype.apply ( thisArg, argArray )<-- two parameters

【讨论】:

  • 谢谢@zack,现在我明白了
【解决方案2】:

因为apply 接受2 个参数。如果没有应用,它将显示 0

(function test() {
  console.log(function() {}.length)
})();

【讨论】:

    【解决方案3】:

    length 属性表示函数期望的参数数量。

    例如:

    function boy() {}
    function girl(name, age) {}
    

    如果你检查第一个函数长度boy.length然后是expected output: 0,因为函数接收到的参数是0。第二个函数接收到2个参数,所以girl.length输出将是2

    快速总结:

    const fn1 = (a    , b    ) => { }
    const fn2 = (a    , ...b ) => { }
    const fn3 = (a    , b = 2) => { }
    const fn4 = (a = 1, b    ) => { }
    fn1.length // -> 2
    fn2.length // -> 1
    fn3.length // -> 1
    fn4.length // -> 0
    

    最后一个 fn4 是最有趣的案例。

    实际上,我会说它更有趣。解释一般区分无默认值和设置为未定义的默认值;但是,它对函数执行没有影响。

    const fn1 = (a            , b            ) => { }
    const fn5 = (a = undefined, b = undefined) => { }
    fn5.length // -> 0
    

    当然,fn1 和 fn5 的行为完全相同。唯一可观察到的区别是函数长度。

    根据规范,在内部,出现在具有默认值的参数之后的没有默认值的参数“被认为是可选的,其默认值未定义”。

    (function test(){
       console.log(function(){}.apply.length);
    })();
    

    在此代码中.apply() 接受2 参数。所以它的长度是2

    【讨论】:

      【解决方案4】:

      通常,apply() 方法以给定的 this 值作为参数调用函数

      【讨论】:

      • 是的,但这并不能回答问题。
      最近更新 更多