Javascript 中 with 语句的未来

2022-01-24 00:00:00 javascript coffeescript ecmascript-5 dsl

我知道 with 语句的用法 在 Javascript 中不推荐 并且在 ECMAScript 5 中被禁止,但它允许人们在 Javascript 中创建一些不错的 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.

例如 CoffeeKup - 模板引擎和 Zappa 网络 DSL.那些使用一些 非常 weird 使用 with 语句的作用域方法来实现 DSLish对他们的感觉.

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.

with 语句和这些类型的 DSL 有没有未来?

Is there any future with the with-statement and these kinds of DSLs?

如果没有 with 语句,是否可以实现这种 DSL 效果?

Can this DSL-effect be achieved without the with-statement?

推荐答案

with 在 ECMAScript 5 中被禁止"是一种常见的误解.

with being "forbidden" in ECMAScript 5 is a common misconception.

只有在 ECMAScript 5 的严格模式下——请注意,这是 opt-in——with 语句是语法错误.因此,您当然仍然可以在完全符合 ECMAScript 5 的实现中使用 with,只要它们出现在非严格(或 Crockford 所说的草率)代码中.它的性能不会很好(因为 with 的存在通常会扼杀现代引擎中的各种优化)但它会起作用.

Only in strict mode of ECMAScript 5 — which is opt-in, mind you — with statement is a syntax error. So you can certainly still use with 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 of with often kills various optimizations in modern engines) but it will work.

ECMAScript 的未来版本很可能基于严格模式行为,尽管也可能是可选的.因此,在将来对脚本进行校对时,遵循严格模式当然是一个好主意.

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.

相关文章