如何检查JavaScript中是否定义了变量?

Mor*_*eng 460 javascript dom undefined

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

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

function profileRun(f) {
    // f: functions to be profiled
    console.profile(f.constructor);
    f();
    console.profileEnd(f.constructor);
}
Run Code Online (Sandbox Code Playgroud)

它在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

    f();

    if (window.console != undefined) {
        console.profileEnd(f.constructor);
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有任何跨浏览器的方式来检查它?