Javascript 中 with 语句的未来
我知道不建议使用 with 语句 在 Javascript 中,在 ECMAScript 5 中被禁止,但它允许人们在 Javascript 中创建一些不错的 DSL。
例如 CoffeeKup 模板引擎和 Zappa 网络 DSL。这些使用了一些非常 奇怪的使用with语句实现DSLish的作用域方法对他们的感觉。
with 语句和这些类型的 DSL 有未来吗?
如果没有 with 语句,可以实现这种 DSL 效果吗?
I know that usage of the with-statement is not recommended in Javascript and is forbidden in ECMAScript 5, but it allows one to create some nice DSLs in Javascript.
For example CoffeeKup-templating engine and the Zappa web DSL. Those uses some very weird scoping methods with the with-statement to achieve DSLish feeling to them.
Is there any future with the with-statement and these kinds of DSLs?
Can this DSL-effect be achieved without the with-statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在coffeescript中,有一个很好的技巧可以在不使用
with
的情况下继续使用花哨的dsls:In coffeescript, there is a nice trick to keep using fancy dsls without using
with
:ECMAScript 5 中“禁止”
是一种常见的误解。
仅在 ECMAScript 5 的严格模式下(请注意,这是选择加入)-
with
语句是语法错误。因此,您当然仍然可以在完全符合 ECMAScript 5 的实现中使用with
,只要它们出现在非严格(或 Crockford 所说的草率)代码中即可。它对于性能来说并不是很好(因为with
的存在常常会杀死现代引擎中的各种优化),但它会起作用。ECMAScript 的未来版本很可能基于严格模式行为,尽管也可能是选择加入的。因此,当涉及到未来的脚本验证时,遵守严格模式无疑是一个好主意。
with
being "forbidden" in ECMAScript 5 is a common misconception.Only in strict mode of ECMAScript 5 — which is opt-in, mind you —
with
statement is a syntax error. So you can certainly still usewith
in fully ECMAScript 5 -compliant implementations, as long as they occur in non-strict (or sloppy, as Crockford calls it) code. It won't be pretty for performance (since mere presence ofwith
often kills various optimizations in modern engines) but it will work.Future versions of ECMAScript are very likely to be based on strict mode behavior, although will also likely be opt-in as well. So conforming to strict mode is certainly a good idea when it comes to future proofing your scripts.
为什么不直接分配一个 var 来指向该对象而不是使用 with 呢?
'with' 样式:
'var' 样式:
Why not just assign a var to point to the object instead of using with?
'with' style:
'var' style:
要回答 Epeli 的问题,请查看 CoffeeMugg,它的功能与 CoffeeKup 的功能相同,但使用了 Adrien 的技术。它使用
this.
而不是with
语句。To answer Epeli's question, take a look at CoffeeMugg which does what CoffeeKup does but using Adrien's technique. It uses
this.
instead of thewith
statement.