在 JavaScript 中,您可以访问函数的“功能属性”,例如 caller
。 (实际上,我什至不知道“功能特性”这个词是否正确。)
例如:
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[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 的原因。
关于javascript - 访问函数属性(.called)而不指定其自己的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23002850/