【问题标题】:Future of the with-statement in JavascriptJavascript 中 with 语句的未来
【发布时间】:2011-03-21 03:37:28
【问题描述】:

我知道在 Javascript 中使用 with-statement is not recommended 并且在 ECMAScript 5 中是被禁止的,但它允许人们在 Javascript 中创建一些不错的 DSL。

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

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

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

【问题讨论】:

  • ES Next quasi-literals 看起来会成为 JS DSL 工具。

标签: javascript dsl coffeescript ecmascript-5


【解决方案1】:

在coffeescript 中,有一个很好的技巧可以在不使用with 的情况下继续使用精美的dsls:

 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");
     });
   }
 */

【讨论】:

  • 啊,太棒了!这几乎和 with-trick 一样干净。有人用这个实现了模板引擎吗?
  • 不这么认为,不过应该可以让coffeekup (github.com/mauricemach/coffeekup) 适应这种效果。
  • 这与 "with" 的作用不同。 "with" 将变量直接放在作用域中,而不是作为 "this" 的属性。
【解决方案2】:

with 在 ECMAScript 5 中被“禁止”是一种常见的误解。

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

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

【讨论】:

    【解决方案3】:

    为什么不直接分配一个 var 来指向对象而不是使用 with?

    'with' 样式:

    with(a_long_object_name_that_is_bloated) {
      propertyA = 'moo';
      propertyB = 'cow';
    }
    

    'var' 样式:

    var o = a_long_object_name_that_is_bloated;
    o.propertyA = 'moo';
    o.propertyB = 'cow';
    

    【讨论】:

      【解决方案4】:

      要回答 Epeli 的问题,请查看 CoffeeMugg,它与 CoffeeKup 一样,但使用了 Adrien 的技术。它使用this. 而不是with 语句。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-06
        • 1970-01-01
        • 2020-12-13
        • 2020-02-29
        • 2011-08-07
        • 2018-09-20
        • 1970-01-01
        相关资源
        最近更新 更多