1. callee \ arguements.callee
是什么?
就是一个指针 可以指向函数本身
1.每个函数都存在一个arguements的对象 尔callee存在于arguements
callee是arguements arguements的属性
callee的使用需要在函数内部进行访问
javascript">function fn(){}
dir(fn)
arguments: null
caller: null
length: 0
name: "fn"
prototype: {constructor: ƒ}
[[FunctionLocation]]: VM96:1
[[Prototype]]: ƒ ()
[[Scopes]]: Scopes[1]
javascript"> function add(a) {
if (a==1) return 1;
return a*arguments.callee(a-1);
//此时可以访问到
//arguments.callee 就等同于自身函数add
}
2.caller
是什么?
指向他的执行者
- caller属于函数的一个属性
javascript"> function a(){
console.log(a.caller)
//此时的a.caller 指向b 因为他在b函数运行
}
function b(){
a()
}
3.callee用处
1.递归
javascript"> function add(a) {
console.log(add.caller)
if (a==1) return 1;
return a*add(a-1);
}
//如果 你把函数赋值给了 别的变量
var other=add;
add=null
other(2)//将会报错 因为return a*add(a-1);时候 add不再是函数
function add(a) {
console.log(add.caller)
if (a==1) return 1;
return a*arguments.callee(a-1);
}
//如果 你把函数赋值给了 别的变量
var other=add;
add=null
other(2)//正常 因为return a*arguments.callee(a-1);
//时候 arguments.callee将会指向other
let a=(function as() {
if (a==1) return 1;
return a*as(a-1);
})
//因为严格模式 不支持arguement 所以可以用以上的方式替代 完成递归