簡體   English   中英

JavaScript中的斷言

[英]Assertions in JavaScript

廣泛閱讀JavaScript中的各種斷言框架。 有沒有任何事實上/最常見的“標准”庫/框架? 選擇一個 - 哪個點最值得注意?

在生產模式下,我能想到的(唯一)要求是接近於零的性能開銷。

兩種可能的解決方

讓您的構建版本腳本刪除Assert行。

要么

讓您的構建腳本覆蓋Assert函數,因此它只是一個空函數。 對此的缺點是,如果你斷言調用中有邏輯[又名斷言(x> 100,“foo”)],那么邏輯[x> 100]仍然會被運行。

這是我使用的:

當我正在處理代碼時,我有initDevMode(); 在我正在使用的文件的頂部,當我准備發布到生產時,我只是刪除該行,所有斷言只是去一個空函數。

/**
 * Log a message to console:
 *  either use jquery's console.error
 *  or a thrown exception.
 *  
 *  call initDevMode(); before use to activate
 *  use with:
 *      assert(<condition>, "message");
 *      eg: assert(1 != 1, "uh oh!");
 *  
 *  Log errors with:
 *       errorLog(message);
 *       eg: errorLog(xhr.status);
 */
assert = function(test, msg) { }
errorLog =function(msg) { }

initDevMode = function() {
    assert = function(test, msg) {
        msg = msg || "(no error message)";
        if(!test) {
            try {
                    throw Error();
                } catch(e) {
                    var foo = e;
                    var lines = e.stack.split('\n');
                    for(i in lines) {
                        if(i > 2) {
                        errorLog(msg + lines[i]);
                    }
                }
            }
        }
        throw("Assertion failed with: " + msg);
    };
    errorLog = function(msg) {
        if(typeof console.error == 'function') { 
            console.error(msg);
        } else {
            function errorLog(msg) {
                console.log("foo");
                setTimeout(function() {
                    throw new Error(msg);
                }, 0);
            }
        }
    };
}

當出於任何原因它不可用時,我使用以下代碼替換console.assert。

它絕對不是事實上的標准,它遠非理想,但它確實滿足了您的要求,即斷言不能在生產模式下進行評估。 此外,它還向您顯示觸發失敗斷言的表達式,這有助於調試。

使用棘手的調用語法(帶有函數表達式)來創建閉包,以便斷言函數可以訪問其調用者可以訪問的相同變量。

我懷疑這有很高的編譯時間和運行時開銷,但我沒有嘗試驗證。

function assert(func) {
    var name;
    if (typeof(ENABLE_ASSERTIONS) !== "undefined" && !ENABLE_ASSERTIONS) {
        return;
    }
    name = arguments.callee.caller;
    name = name ? name.name : "(toplevel)";
    if (!func()) {
        throw name + ": assertion failed: " + ('' + func).replace(/function[^(]*\([^)]*\)[^{]*{[^r]*return/, '').replace(/;[ \t\n]*}[ \t\n]*$/, '');
    }
}

使用它看起來像:

function testAssertSuccess() {
    var i = 1;
    assert(function() { return i === 1; });
}
function testAssertFailure() {
    var j = 1;
    assert(function() { return j === 2; });
}
ENABLE_ASSERTIONS = true;
testAssertSuccess();
testAssertFailure();

HTH!

看看Jascree ; 基本上它是一個工具,可以從代碼中刪除幾乎任意邏輯的斷言。 使用批處理器生成生產代碼或fastcgi支持的腳本目錄非常方便,可以在需要測試性能/配置代碼時使用。

暫無
暫無

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

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