为什么80%的码农都做不了架构师?>>>   【JavaScript】callee 与 caller-编程之家

callee

callee是函数参数arguments对象的一个属性,它指向参数arguments对象所在的函数自身。

function foo (x) {console.log(arguments.callee);return x;
}foo();

从控制台中可以看到打印的结果为:

ƒ foo (x) {console.log(arguments.callee);return x;
}

它的作用就是在函数内部通过调用arguments.callee()来代替调用函数自身foo()。举个栗子,写一个阶乘函数:

function sum(num){if(num <= 1){return 1;}else{// 以往的递归写法// return num * sum(num-1); return num * arguments.callee(num-1);}
}console.log(sum(3)); // 打印结果为 6

caller

caller是函数对象的一个属性,该属性保存着调用当前函数的对象,还是举个栗子:

function foo (x) {console.log(foo.caller);return x + 1;
}function too () {foo(3)
}too();

打印结果为:

ƒ too () {foo(3)
}

因为foo函数是在too函数内部调用的,那么调用foo函数的对象即为too,所以caller指向的就是too这个函数对象。

转载于:https://my.oschina.net/cc4zj/blog/3051654