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

后端 未结 30 1791
伪装坚强ぢ
伪装坚强ぢ 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:29

    Using "with" can make your code more dry.

    Consider the following code:

    var photo = document.getElementById('photo');
    photo.style.position = 'absolute';
    photo.style.left = '10px';
    photo.style.top = '10px';
    

    You can dry it to the following:

    with(document.getElementById('photo').style) {
      position = 'absolute';
      left = '10px';
      top = '10px';
    }
    

    I guess it depends whether you have a preference for legibility or expressiveness.

    The first example is more legible and probably recommended for most code. But most code is pretty tame anyway. The second one is a bit more obscure but uses the expressive nature of the language to cut down on code size and superfluous variables.

    I imagine people who like Java or C# would choose the first way (object.member) and those who prefer Ruby or Python would choose the latter.

提交回复
热议问题