Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

初识 JavaScript 函数 Arguments 模拟重载 #192

Open
toFrankie opened this issue Feb 26, 2023 · 0 comments
Open

初识 JavaScript 函数 Arguments 模拟重载 #192

toFrankie opened this issue Feb 26, 2023 · 0 comments
Labels
2019 2019 年撰写 JS 与 JavaScript、ECMAScript 相关的文章 前端 与 JavaScript、ECMAScript、Web 前端相关的文章

Comments

@toFrankie
Copy link
Owner

toFrankie commented Feb 26, 2023

在 JavaScript 中并没有重载函数的功能,但每个函数中的 Arguments 对象可以模拟重载的实现。

1. 通过下标访问实参:

arguments 不是一个数组对象,没有数组对象所有的属性和方法,但通过 arguments[0]arguments[1] 等方式获取实参。

function demo() {
  let str = ''
  for (let i = 0; i < arguments.length; i++) {
    str += arguments[i] + ', '
  }
}
console.log(demo('小明', '小红')) // 输出:小明, 小红,

2. 实现重载

利用 Arguments 对象实现函数重载的方式可以有几种,除了根据参数的个数,还可以根据传入参数的类型、或者利用参数中特殊的参数值来执行不同的操作。

// 通过参数个数实现重载
function overloadDemo() {
  switch (arguments.length) {
    case 0:
      console.log(0)
      break
    case 1:
      console.log(1)
      break
    default:
      console.log(arguments.length)
      break
  }
}
overloadDemo('name') // 输出:1

3. callee 属性

Arguments 对象的 callee 属性指向的是正在被执行的 Function 对象。常常利用该属性实现递归。

function sum(n) {
  if (n == 1) {
    return 1
  } else {
    return n + arguments.callee(n - 1)
  }
}
console.log(sum(5)) // 输出:15

但是 arguments.calleearguments.caller 已经在 ES5 严格模式中禁用,将来也会彻底移除。

@toFrankie toFrankie added 前端 与 JavaScript、ECMAScript、Web 前端相关的文章 JS 与 JavaScript、ECMAScript 相关的文章 labels Feb 26, 2023
@toFrankie toFrankie added the 2019 2019 年撰写 label Apr 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
2019 2019 年撰写 JS 与 JavaScript、ECMAScript 相关的文章 前端 与 JavaScript、ECMAScript、Web 前端相关的文章
Projects
None yet
Development

No branches or pull requests

1 participant