【问题标题】:Why does the javascript apply function work recursively?为什么javascript应用函数递归工作?
【发布时间】:2018-08-17 05:04:40
【问题描述】:

我正在学习 John Resig 的 javascript 函数重载。

https://johnresig.com/blog/javascript-method-overloading/

我在练习此链接上的示例时有一个问题:

function addMethod (object, name, fn) {
  var old = object[ name ]
  object[ name ] = function () {
    console.log(fn.length)
    console.log(arguments.length)
    if (fn.length === arguments.length) {
      let ret = fn.apply(this, arguments)
      console.log(ret)
      return ret
    } else if (typeof old === 'function') {
      let ret = old.apply(this, arguments)
      console.log(ret)
      return ret
    }
  }
}

addMethod 用于函数重载,实际函数内部的行为是我调用函数时的行为。

执行apply函数时出现问题。 如果函数参数不同,则调用old.apply 函数。 如果调用这个函数,它会递归地工作。

例如,如果没有实际的 function 参数,则第一个 argument.length 为 2 并调用 old.apply。同样,在递归调用的函数中,arguments.length 的值为 1。为什么会递归调用 apply 函数?

ps。 AddMethod:

function Users() {}
addMethod(Users.prototype, 'find', function () {
  console.log('ARG 0')
  // Find all users...
})

addMethod(Users.prototype, 'find', function (name, age) {
  console.log('ARG 1')
  // Find a user by name
})

调用函数:

var users = new Users()
users.find() // Finds all
users.find('John') // Finds users by name

【问题讨论】:

  • “递归调用”是什么意思?您是在观察递归,还是假设会有递归?上面的输出在你的测试中是什么样子的?
  • 正确。我调试了一下,递归调用了apply函数。
  • 我添加了我的附加代码。当我调用 users.find() 函数和不同的 arguments.length(0) 和 fn.length(2) 时,调用了 old.apply。之后,fn.length 为 1,argument.length 为 0

标签: javascript overloading apply


【解决方案1】:

当你执行时

addMethod(Users.prototype, 'find', function () {...}

然后将Users.prototype.find 设置为包含语句中的函数(fn)的包装函数。

然后你执行

addMethod(Users.prototype, 'find', function (name, age) {...}

将之前的包装函数转移到旧变量中,并将新的包装函数绑定到Users.prototype.find

当您调用users.find()(不带参数)时,您似乎调用了您的find 函数(包含console.log 语句),但实际上您调用的是绑定到Users.prototype.find 的最后定义的包装函数。变量被打印出来。 由于参数不匹配,包装函数改为调用旧的“包装”函数(在old 变量中)。第二次打印变量。然后调用addMethod 定义的实际“查找”函数。

这并不是真正的递归,您只是存储了两个函数,第一个(包装器)函数调用了第二个。然后就结束了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2021-10-28
    • 2023-02-07
    • 2012-01-11
    • 2016-02-04
    相关资源
    最近更新 更多