Are there legitimate uses for JavaScript's “with” statement?

后端 未结 30 2376
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 04:22

Alan Storm\'s comments in response to my answer regarding the with statement got me thinking. I\'ve seldom found a reason to use this particular language feature, and had ne

30条回答
  •  佛祖请我去吃肉
    2020-11-22 05:05

    Here's a good use for with: adding new elements to an Object Literal, based on values stored in that Object. Here's an example that I just used today:

    I had a set of possible tiles (with openings facing top, bottom, left, or right) that could be used, and I wanted a quick way of adding a list of tiles which would be always placed and locked at the start of the game. I didn't want to keep typing types.tbr for each type in the list, so I just used with.

    Tile.types = (function(t,l,b,r) {
      function j(a) { return a.join(' '); }
      // all possible types
      var types = { 
        br:  j(  [b,r]),
        lbr: j([l,b,r]),
        lb:  j([l,b]  ),  
        tbr: j([t,b,r]),
        tbl: j([t,b,l]),
        tlr: j([t,l,r]),
        tr:  j([t,r]  ),  
        tl:  j([t,l]  ),  
        locked: []
      };  
      // store starting (base/locked) tiles in types.locked
      with( types ) { locked = [ 
        br,  lbr, lbr, lb, 
        tbr, tbr, lbr, tbl,
        tbr, tlr, tbl, tbl,
        tr,  tlr, tlr, tl
      ] } 
      return types;
    })("top","left","bottom","right");
    

提交回复
热议问题