【发布时间】: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