javascript中caller和callee区别以及使用场景

英文翻译

caller 

n. 访客;[通信] 呼叫者;打电话者;召集员

  • callee
    • n. 被召者


caller

理解为指的是调用当前函数的函数,也就是调用者,如果没有其他函数调用的话就是null,举个栗子如果callerTest()是直接执行的函数,那么callerTest.caller===null,如果test()去调用callerTest(),那么callerTest.caller===test,具体可以看看下面这段代码

function callerTest(){
	console.log(callerTest.caller);
}
function test(){
	callerTest();
}
test();//test
callerTest();//null


callee

可以理解为当前执行的函数即被调用的函数,也就是被调用者,举个栗子如果calleeTest为当前执行的函数,那么arguments.callee===calleeTest,因此也就有了callee的一个应用,可以用于递归调用,虽然可以直接写为calleeTest,但是这样显然耦合度比较高,不利于代码维护,而如果写成arguments.callee的话就可以降低耦合度

代码

function calleeTest(){
	console.log(calleeTest===arguments.callee);
}
function test(){
	calleeTest();
}
test();//true
calleeTest();//true

猜你喜欢

转载自blog.csdn.net/qin_shuo/article/details/80314343