[英]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.