Epe*_*eli 8 javascript dsl coffeescript ecmascript-5
我知道在Javascript中不推荐使用with -statement ,在ECMAScript 5中禁止使用with -statement ,但是它允许用Javascript创建一些不错的DSL.
例如CoffeeKup -templating引擎和Zappa web DSL.那些使用一些非常 奇怪的范围方法和with -statement来实现DSLish的感觉.
with -statement和这些类型的DSL 有未来吗?
没有with -statement 可以实现这种DSL效果吗?
Adr*_*ien 10
在coffeescript中,有一个很好的技巧来继续使用花哨的dsls而不使用with:
using = (ob, fn) -> fn.apply(ob)
html =
head : (obj) -> # implementation
body : (fn) -> # implementation
div : (str) -> # implementation
using html, ->
@head
title: "My title"
@body =>
@div "foo bar"
@div "qux moo"
/*
in pure javascript you'd be using
with(html){
head({title:"My title"});
body(function(){
div("foo bar");
div("qux moo");
});
}
*/
Run Code Online (Sandbox Code Playgroud)
with在ECMAScript 5中被"禁止"是一种常见的误解.
只有在ECMAScript 5的严格模式下 - 这是选择加入,请注意 - with语句是语法错误.因此,您当然可以with完全使用完全符合ECMAScript 5的实现,只要它们出现在非严格(或者像Crockford称之为草率)代码中.它对性能来说不是很好(因为仅仅存在with会在现代引擎中杀死各种优化),但它会起作用.
ECMAScript的未来版本很可能基于严格模式行为,尽管也可能选择加入.因此,在未来校对脚本时,遵循严格模式肯定是一个好主意.