我正在尝试创建一个简单的调试函数,它只显示函数的调用者,如下所示:
function xe() {
console.log(xe.caller().name)
}
有了这个,我就可以添加
xe()
到一个函数,它将记录对该函数的调用——只是一个简短的、简单的补充,以帮助调试。调试糖,可以这么说。不幸的是,我从主题行中得到了错误:
TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.
我正在使用 Babel/ES6,它注入(inject)了
"use strict"
在每个模块的顶部。这可能是原因,但搜索已经产生了关于为什么引发错误的有限信息,我想更好地理解它。如果严格模式是问题所在,我不希望为整个项目禁用严格模式——仅针对模块/功能。
最佳答案
这就是原因。 From MDN :
in strict mode it's no longer possible to "walk" the JavaScript stack via commonly-implemented extensions to ECMAScript. In normal code with these extensions, when a function fun is in the middle of being called, fun.caller is the function that most recently called fun, and fun.arguments are the arguments for that invocation of fun. Both extensions are problematic for "secure" JavaScript because they allow "secured" code to access "privileged" functions and their (potentially unsecured) arguments. If fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw when set or retrieved:
如果你在做 ES6,一般情况下你不能禁用严格模式。它在 certain conditions 期间是隐含的例如在 ES6 模块中。
如果您只是在调试,我建议您在调试器中使用断点并检查堆栈帧,但我相信您已经知道了。
如果您只是输出调试信息,我想只需读取 Error 对象的堆栈:
console.log(new Error().stack);
您可以globaly disable (但我知道这不是你想要的)
use strict
使用 babel 使用:require("6to5").transform("code", { blacklist: ["useStrict"] });
或者
$ 6to5 --blacklist useStrict
如果您必须在模块级别上剥离它,我怀疑您必须自己做。基本字符串替换可能吗?
此外,正如 ES5 中所指出的那样。应该是
xe.caller.name
而不是 xe.caller().name
或者您将重新调用该函数。
关于javascript - 'caller' 和 'arguments' 是受限函数属性,无法在此上下文中访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921189/