059_arguments.callee和arguments.callee.caller

本文详细探讨了JavaScript中arguments.callee和arguments.callee.caller的概念,通过实际代码演示了它们如何跟踪函数调用关系,并展示了如何利用它们生成唯一ID和追踪顶层调用。此外,还涉及到了函数对象和闭包的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. arguments.callee指向函数本身。

2. arguments.callee.caller指向调用函数的函数。

3. 例子

3.1. 代码

<!DOCTYPE html>
<html>
	<head>
		<title>arguments.callee和arguments.callee.caller</title>
	</head>
	<body>
		<script type="text/javascript">
			// arguments.callee指向函数本身
			// arguments.callee.caller指向调用函数的函数
			function fun1(){
				console.log(arguments.callee);
				console.log(arguments.callee.caller);
			}
			function fun2(){
				console.log(arguments.callee);
				console.log(arguments.callee.caller);
				fun1();
			}
			function fun3(){
				console.log(arguments.callee);
				console.log(arguments.callee.caller);
				fun2();
			}
			fun3();

			// 利用arguments.callee生成学生唯一id
			var tools = {
				id: function(){
					return (arguments.callee.id === undefined) ? (arguments.callee.id = 1001) : (++arguments.callee.id);
				}
			}

			function ClassPeople(firstName, lastName){
				this.id = tools.id();
				this.firstName = firstName;
				this.lastName = lastName;
			}

			ClassPeople.prototype.fullName = function(){
				return this.firstName + this.lastName;
			};

			var zhangsan = new ClassPeople('张', '三');
			console.log('id = ' + zhangsan.id + ', fullName = ' + zhangsan.fullName());

			var lisi = new ClassPeople('李', '四');
			console.log('id = ' + lisi.id + ', fullName = ' + lisi.fullName());

			// 利用arguments.callee.caller找到顶层调用函数
			function topFun1(){
				var c = arguments.callee.caller;

				do{
					console.log(c.name);
				}while(c = c.caller);
			}
			function topFun2(){
				topFun1();
			}
			function topFun3(){
				topFun2();
			}
			topFun3();
		</script>
	</body>
</html>

3.2. 效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值