Future of the with-statement in Javascript

自闭症网瘾萝莉.ら 提交于 2019-12-21 01:16:14

问题


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?


回答1:


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 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.

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.




回答2:


In coffeescript, there is a nice trick to keep using fancy dsls without using 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");
     });
   }
 */



回答3:


Why not just assign a var to point to the object instead of using with?

'with' style:

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

'var' style:

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



回答4:


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 the with statement.



来源:https://stackoverflow.com/questions/5373577/future-of-the-with-statement-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!