JavaScript--函数的参数列表以及arguments的用法

函数声明时,参数的问题

即使函数在定义时没有显示声明任何参数,你仍然可以在调用该函数时传递参数
这是因为 JavaScript 函数内部有一个隐含的 arguments 对象,它包含了所有传递给函数的参数。

示例

我们来通过一些示例代码来更清楚地说明这一点。

示例 1:没有参数的函数

function example() {
  console.log(arguments); // 输出所有传入的参数
}

example(1, 2, 3); // 输出:[1, 2, 3]

在这里插入图片描述

示例 2:函数声明了参数

function example(a, b, c) {
  console.log(a, b, c); // 输出具体的参数
  console.log(arguments); // 输出所有传入的参数
}

example(1, 2, 3); // 输出:1 2 3  [1, 2, 3]
example(1); // 输出:1 undefined undefined  [1]

使用 arguments 对象

在没有声明参数的函数中,arguments 对象仍然可以捕获所有传入的参数:

function example() {
  for (let i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

example(1, 2, 3); // 输出:1 2 3

应用在 newCall 方法中

newCall 方法可以接收多个参数,并通过 arguments 对象处理这些参数:

Function.prototype.newCall = function (context) {
  if (typeof this !== "function") {
    throw new TypeError("调用的不是函数");
  }

  context = context || window;

  const args = Array.prototype.slice.call(arguments, 1);

  const fnSymbol = Symbol();

  context[fnSymbol] = this;

  const result = context[fnSymbol](...args);

  delete context[fnSymbol];

  return result;
};

function person(a, b, c, d) {
  console.log(this.name);
  console.log(a, b, c, d);
}

let egg = {
  name: "测试",
};

person.newCall(egg, '1', '2', '3', '4'); // 输出:测试 1 2 3 4

总结

在 JavaScript 中,即使函数没有声明任何参数,也可以传入参数。函数内部通过 arguments 对象捕获所有传递的参数。这种特性使得函数调用非常灵活,特别是在实现类似 Function.prototype.call 或 Function.prototype.apply 这样的动态方法时尤为有用。

  • 12
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值