簡體   English   中英

IE9是否支持console.log,它是真正的功能嗎?

[英]Does IE9 support console.log, and is it a real function?

在哪種情況下,Internet Explorer 9中定義了window.console.log

即使window.console.log定義, window.console.log.applywindow.console.log.call是不確定的。 為什么是這樣?

[IE8的相關問題:IE8 中的console.log發生了什么變化? ]

在Internet Explorer 9(和8)中,只有在為特定選項卡打開開發人員工具時才會公開console對象。 如果隱藏該選項卡的開發人員工具窗口,則對於您導航到的每個頁面, console對象將保持公開狀態。 如果打開新選項卡,還必須打開該選項卡的開發人員工具,以便公開console對象。

console對象不是任何標准的一部分,是文檔對象模型的擴展。 與其他DOM對象一樣,它被認為是一個宿主對象,不需要從Object繼承,也不需要從Function繼承它的方法,就像本機ECMAScript函數和對象一樣。 這就是applycall未定義的原因。 在IE 9中,大多數DOM對象都得到了改進,可以從本機ECMAScript類型繼承。 由於開發人員工具被認為是IE的擴展(雖然是內置擴展),但他們顯然沒有得到與其他DOM相同的改進。

對於它的價值,您仍然可以在console方法上使用一些具有一點bind()魔法的Function.prototype方法:

var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"

這個console.log問題的一個簡單解決方案是在JS代碼的開頭定義以下內容:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

這適用於所有瀏覽器。 當調試器未激活時,這將為console.log創建一個虛函數。 當調試器處於活動狀態時,方法console.log已定義並正常執行。

我知道這是一個非常古老的問題但是覺得這增加了如何處理控制台問題的有價值的替代方案。 在調用console。之前放置以下代碼。*(所以你的第一個腳本)。

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

參考:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js

console.log僅在控制台打開時定義。 如果要在代碼中檢查它,請確保在窗口屬性中檢查它

if (window.console)
    console.log(msg)

這會在IE9中引發異常,無法正常工作。 不要這樣做

if (console) 
    console.log(msg)

在閱讀了Marc Cliament上面評論的文章之后,我現在將我的通用跨瀏覽器console.log函數更改為如下所示:

function log()
{
    "use strict";

    if (typeof(console) !== "undefined" && console.log !== undefined)
    {
        try
        {
            console.log.apply(console, arguments);
        }
        catch (e)
        {
            var log = Function.prototype.bind.call(console.log, console);
            log.apply(console, arguments);
        }
    }
}

我想提一下,如果您使用console.log並在所有版本的Windows上關閉開發人員工具,IE9不會引發錯誤。 在XP上它確實如此,但在Windows 7上卻沒有。 因此,如果你放棄了對WinXP的支持,你可以直接使用console.log。

怎么樣...

console = { log : function(text) { alert(text); } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM