4

我正在使用 Google Closure Library 及其编译器创建一个应用程序。要调试我使用的值console.log()。编译它会抛出以下异常JSC_UNDEFINED_VARIABLE. variable console is undeclared at ...。为了解决这个错误,我只需要window.console.log()改用。
我还想测量一个函数所花费的时间。Firebug 有两个很好的功能console.time(name),并且console.timeEnd(name)很容易做到这一点。不幸的是,闭包编译器不支持这些函数并抛出以下警告JSC_INEXISTENT_PROPERTY. Property time never defined on Window.prototype.console at ...。不幸的是,您无法通过添加来解决此警告window
我还查看了该库,但 goog.debug.Console 没有我需要的功能。
我之前使用过的另一个解决方案如下

var start = new Date();  
// do something
var end = new Date();

// do some calculation to get the ms for both start and end
var startMS = ....;
var endMS = .....;
// get the difference and print it
var difference = (endMS - startMS) / 1000;
console.log('Time taken for something: ' + difference);

代码有点多,如果你经常使用的话,有两个功能的版本会很棒:

window.console.time("timeTaken");
// do something
window.console.timeEnd("timeTaken");

这会打印出开始和结束之间的 MS。但如上所述,这不适用于闭包编译器。window.console.time()有没有人对此有解决方案,我如何使用这两个功能window.console.timeEnd()?或者 goog.closure 提供的另一种解决方案,但我还没有找到?

4

2 回答 2

4

您只需要将它们添加到您正在使用的外部。

于 2011-10-20T16:20:09.427 回答
1

如果您不想/不能使用 externs,您可以使用基于字符串的属性轻松引用“未声明”对象:

window['console']['log']('Hello Console!');
window['console']['time']('timeTaken');
...

但是你必须小心,因为如果time属性不存在或者它不是函数,第二行可能会抛出错误。

于 2012-11-10T17:09:14.853 回答