JavaScript 中的断言
广泛阅读 JavaScript 中的各种断言框架。是否有任何事实上的/最常见的“标准”库/框架?选择时——哪些点最值得关注?
我能想到的(唯一)要求是在生产模式下接近于零的性能开销。
Extensively reading about various assertion frameworks in JavaScript. Is there any kind of de-facto/most common "standard" library/framework? When selecting one - which points are most worth noticing?
The (only) requirement I can think about is close-to-zero performance overhead when in production mode.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两种可能的解决方案:
让您的构建发布脚本删除 Assert 行。
或者
让您的构建脚本覆盖 Assert 函数,使其只是一个空函数。这样做的缺点是,如果您断言调用中有逻辑[又名断言(x> 100,“foo”)]而不是逻辑[x>; 100]仍将运行。
Two possible solutions:
Have your build release script remove the Assert lines.
or
Have your build script override the Assert function so it is just an empty function. Downside to this is if you assert call has logic in it [aka assert( x > 100 , "foo" )] than that logic [x > 100] is still going to be run.
这是我使用的:
当我处理代码时,我有 initDevMode();在我正在使用的文件的顶部,当我准备好发布到生产环境时,我只需删除该行,所有断言都将转到一个空函数。
Here is what I use:
When I'm working on the code I have initDevMode(); at the top of the file I'm working with, and when I'm ready to release to production, I just remove that line and all the asserts just go to an empty function.
当 console.assert 由于某种原因不可用时,我使用以下内容来替换它。
它绝对不是事实上的标准,而且远非理想,但它确实满足了您的要求,即不在生产模式下评估断言。此外,它还向您显示触发失败断言的表达式,这有助于调试。
扭曲的调用语法(带有函数表达式)用于创建一个闭包,以便断言函数可以访问其调用者可以访问的相同变量。
我怀疑这会产生很高的编译时和运行时开销,但我还没有尝试验证这一点。
使用它看起来像:
HTH!
I use the following to replace console.assert when it's unavailable for whatever reason.
It's definitely not a de-facto standard, and it is far from ideal, but it does satisfy your requirement that the assertion not be evaluated in production mode. Also, it shows you the expression that triggered the failed assertion, which aids debugging.
The screwy calling syntax (with a function expression) is there to create a closure, so that the assert function has access to the same variables that its caller had access to.
I suspect that this has high compile-time and run-time overhead, but I haven't attempted to verify that.
Using it looks like:
HTH!
看看 Jascree;基本上,它是一个可以从代码中删除具有几乎任意逻辑的断言的工具。它可以方便地用作批处理器来生成生产代码,或者用作 fastcgi 支持的脚本目录,当您需要测试性能/分析代码时可以使用它。
Take a look to Jascree; basically it is a tool that can remove assertions with almost arbitrary logic from your code. It is handy to use as a batch processor to generate your production code or for a fastcgi-backed scripts directory that you can use when you need to test performance/profile your code.