web-dev-qa-db-ja.com

定義されていない場合、jsはconsole.logをオーバーライドします

どちらのソリューションをお勧めしますか、2番目の方が簡単です(コードが少ない)が、それを使用すると欠点がありますか?

First:(グローバルデバッグフラグを設定)

// the first line of code
var debug = true;
try {
    console.log
} catch(e) {
    if(e) {
        debug=false;
    }
};
// Then later in the code
if(debug) {
    console.log(something);
}

2番目: console.logを上書き

try {
    console.log
} catch(e) {
    if (e) {
        console.log = function() {}
    }
};
// And all you need to do in the code is
console.log(something);
27
Radu Maris

どちらでもありませんが、2番目のバリエーションです。 try...catchをなくして、コンソールオブジェクトの存在を適切に確認します。

if (typeof console == "undefined") {
    window.console = {
        log: function () {}
    };
}

console.log("whatever");
55
Andy E

または、コーヒースクリプトで:

window.console ?=
    log:-> #patch so console.log() never causes error even in IE.
6
Jameson Quinn

編集:アンディの答え は、以下に掲載したクイックハックよりもはるかにエレガントです。

私は通常、このアプローチを使用しています...

// prevent console errors on browsers without firebug
if (!window.console) {
    window.console = {};
    window.console.log = function(){};
}
3
Frankie

私は過去に同様のバグに直面したことがあり、以下のコードでそれを克服しました:

if(!window.console) {
    var console = {
        log : function(){},
        warn : function(){},
        error : function(){},
        time : function(){},
        timeEnd : function(){}
    }
}
1
Suresh

私は他の回答と同様にこの投稿に出くわしました:

http://jennyandlih.com/resolved-logging-firebug-console-breaks-ie

0
David

以下はあなたが探しているものを実現します:

window.console && console.log('foo');
0
Mike Kormendy
window.console = window.console || {};
window.console.log = window.console.log || function() {};
0
Sean