经过一番探索,我想出了this SO thread,因此在此基础上,我制作了一个非常非常实用的解决方案(在 Chrome 和 FF 中......不确定 IE,但我对此表示怀疑)作品)。 警告:这非常适合我自己的使用,因此您的里程肯定会有所不同。无论如何,这是我的代码:
getLogLocation: function() {
var ua = navigator.userAgent;
var isFF = ua.search(/firefox/i) !== -1 ? true : false;
var isChrome = ua.search(/chrome/i) !== -1 ? true : false;
if (isFF || isChrome) {
var stack = Error().stack,
cname = '',
funcPattern,
classPattern = /.*\/(.*)\.js/; // looking for something between the last backslash and .js
if (stack) {
var stacks = stack.split('\n');
if (stacks) {
var theStack;
// the browsers create the stack string differently
if (isChrome) {
// the stack has getClassName, then logMessage, then our calling class, but Chrome has some added garbage
theStack = stacks[4];
funcPattern = /.*\.(.*)\s+\(/; // looking for something between a period and the first paren
}
else {
theStack = stacks[2];
funcPattern = /^\.*(.*)\@/; // looking for something between a period and an @ symbol
}
var matches = theStack.match(classPattern);
cname = matches[1] + '::';
matches = theStack.match(funcPattern);
cname += matches[1] + ':';
}
}
return cname;
}
}
如果你好奇我的堆栈是什么样的,下面是相关的行:
Firefox(删掉很多行)
".getClassName@http://127.0.0.1/javascripts/app/mixins/ConsoleMixin.js?_dc=1383836090216:72
.logMessage@http://127.0.0.1/javascripts/app/mixins/ConsoleMixin.js?_dc=1383836090216:31
.constructor@http://127.0.0.1/javascripts/app/BaseController.js?_dc=1383836089659:39
..."
Chrome(前两行是我必须容纳的垃圾...之后,它类似于FF的堆栈字符串)
"Error
at Error (<anonymous>)
at Ext.define.getLogLocation (http://127.0.0.1/javascripts/app/mixins/ConsoleMixin.js?_dc=1383836606405:72:19)
at Ext.define.logMessage (http://127.0.0.1/javascripts/app/mixins/ConsoleMixin.js?_dc=1383836606405:31:24)
at new Ext.define.constructor (http://127.0.0.1/javascripts/app/BaseController.js?_dc=1383836606265:39:14)
..."
请参阅this jsFiddle 以获取工作示例...必须更改堆栈值,因为我们不再使用 Ext JS。
现在,稍微解释一下。 getLogLocation 作为一个函数存在于 Ext JS 类 (ConsoleMixin) 中,ConsoleMixin 内部的另一个函数 (logMessage) 调用 getLogLocation,而 logMessage 由我们外部类的函数 (constructor) 调用,这就是为什么我必须补偿前 2 个堆栈值。就像我说的,非常 hacky 并且特定于我的需要,但希望有人可以使用它。