460

如何检查是否以跨浏览器方式定义的 JavaScript 变量?

我在使用 FireBug 日志编写一些 JavaScript 时遇到了这个问题。我写了一些如下代码:

function profileRun(f) {
    // f: functions to be profiled
    console.profile(f.constructor);
    f();
    console.profileEnd(f.constructor);
}

它在 FireFox/FireBug 中运行良好,但在 IE8 RC1 中报告错误。所以,我想检查一下执行环境中是否存在控制台变量。

下面的代码在 FireFox 中运行良好,但在 IE8 RC1 中却不行。

function profileRun(f) {
    if (console != undefined) {
        console.profile(f.constructor);
    }

    f();

    if (console != undefined) {
        console.profileEnd(f.constructor);
    }
}

但是,如果我这样做。它适用于 IE8 RC1。为什么?

function profileRun(f) {
    if (window.console != undefined) {
        console.profile(f.constructor);
    }

    f();

    if (window.console != undefined) {
        console.profileEnd(f.constructor);
    }
}

有没有跨浏览器的方法来检查它?

4

0 回答 0