【发布时间】:2013-06-27 20:52:11
【问题描述】:
是否有可能找出调用函数的位置?如果是,那么 如何检测一个函数是从全局范围、另一个函数还是浏览器控制台调用的?
看看下面的例子:
<script>
function myFunc1() {
// some code
myFunc2(); // I was called from myFunc1()
}
function myFunc2() {
var callerName = new String;
callerName = arguments.callee.caller.name;
// some code
alert('I was called from ' + callerName + ' function');
}
myFunc2(); // I was called from global scope
</script>
我知道上面示例中的这一行 callerName = arguments.callee.caller.name; 会给我调用函数的名称。 但我不知道如何检测函数是否从全局调用 例如,如果我更改myFunc2() 并添加if else 语句来检查arguments.callee.caller.name 是否返回undefined 值,知道这会发生,当从全局范围调用函数时:
myFunc2() {
var callerName = new String;
callerName = arguments.callee.caller.name;
if(callerName == undefined) {
alert('I was called from global scope');
} else {
alert('I was called from ' + callerName + ' function');
}
}
但是,如果从全局范围调用 myFunc2(),这将不起作用,并且 callerName = arguments.callee.caller.name; 将导致 JavaScript 抛出以下错误:
TypeError: 'null' is not an object (evaluating 'arguments.callee.caller.name')
所以我回到第一方,问题仍然存在:
- 如何检测是否从全局范围调用函数?
- 如果它是从全局范围调用的,是从浏览器控制台调用的吗?
【问题讨论】:
-
x = arguments.callee.caller ? arguments.callee.caller.name : "global";我想会修复你的 TypeError 。null.name没有意义,会产生错误。 -
这行得通,但你能解释一下如何吗?此语句中发生了什么:
x = arguments.callee.caller ? arguments.callee.caller.name -
?是二元运算符。x = arguments.callee.caller ? arguments.callee.caller.name : "global";将评估(boolean) arguments.callee.caller。如果这是真的,那么它会将arguments.callee.caller.name分配给x。如果它是假的,那么它会将"global"分配给x。(boolean) null是false,防止代码尝试获取它的名称。 -
所以
callerName = arguments.callee.caller ? arguments.callee.caller.name : "global";等于:if(arguments.callee.caller) { callerName = arguments.callee.caller.name; } else { callerName = "global"; } -
是的,但是在这种情况下二元运算符更容易阅读。
标签: javascript function call