callee和caller的使用

callee

callee是arguments对象中的一个方法,功能是引用arguments所在的函数。

案例:

//命名函数
function fn(){console.log(arguments.callee)}
fn()
结果如下:
//ƒ fn(){console.log(arguments.callee)}
//匿名函数
(function(){console.log(arguments.callee)}())
结果如下:
//ƒ (){console.log(arguments.callee)}

无论是匿名函数或者是命名函数,通过arguments.callee都能引用。

arguments.callee使用

一般使用在递归中:在匿名函数中需要调用自身,可以使用arguments.callee.

案例:

	//匿名函数递归(function (n){if(n > 100){console.log(n) //101return ;}n += 2return arguments.callee(n)}(1))//命名函数递归function fnOne(a){if(a > 100){console.log(a) //101return ;}a += 2return fnOne(a) }fnOne(1)//命名函数递归function fnTwo(b){if(b > 100){console.log(b) //101return ;}b += 2return arguments.callee(b)}fnTwo(1)

caller

caller是arguments.callee的一个属性。谁调用了它所处的函数,caller的值就是谁。

案例:

function a(){console.log(arguments.callee.caller)
}
function b(){a()
}
b()
打印结果如下:
//ƒ b(){
//	a()
//}分析:因为b函数调用了a函数,所以在a函数中的arguments.callee.caller指的就是b函数.

callee和caller在严格模式下是无法使用的。

"use strict";//使用严格模式function a(){console.log(arguments.callee.caller)
}
function b(){a()
}
b()

控制台报错:
在这里插入图片描述


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部