在
JavaScript中,您可以访问函数的“功能属性”,例如调用者. (实际上,我甚至不知道“功能属性”是否是一个正确的词.)
例如:
func0 = function() {
console.log(typeof func0.caller)
}
func1 = func0
func1()
var o = { func2: func0, func3: function(){ console.log(typeof o.func3.caller) } }
o.func2()
o.func3()
如您所见,您必须先提供函数名称,然后才能添加.caller.但如果该函数是匿名的或由于某种原因我不想使用该名称(也许我计划在将来重命名该函数):我仍然可以访问调用者吗?
最佳答案 您正在访问的是为每个函数“分配”的参数对象.所以你不要使用函数名.您使用arguments对象.
arguments对象就像一个数组,所以arguments [0]返回传递给函数的第一个参数.
arguments.length
// a property of the arguments object that tells you how many arguments the function has
arguments.caller
// reference to the function that invoked the current function.
arguments.callee() will call the function recursively. Its a reference to the currently executing function.
你是这个意思吗?
Use arguments.callee.caller
似乎这个工作的原因是因为arguments.callee给你一个当前正在执行的函数的引用,然后arguments.caller引用调用该函数的函数(实际上是相同的函数).也许这就是为什么使用arguments.caller是不可取的.