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

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

    Visual Basic.NET has a similar With statement. One of the more common ways I use it is to quickly set a number of properties. Instead of:

    someObject.Foo = ''
    someObject.Bar = ''
    someObject.Baz = ''
    

    , I can write:

    With someObject
        .Foo = ''
        .Bar = ''
        .Baz = ''
    End With
    

    This isn't just a matter of laziness. It also makes for much more readable code. And unlike JavaScript, it does not suffer from ambiguity, as you have to prefix everything affected by the statement with a . (dot). So, the following two are clearly distinct:

    With someObject
        .Foo = ''
    End With
    

    vs.

    With someObject
        Foo = ''
    End With
    

    The former is someObject.Foo; the latter is Foo in the scope outside someObject.

    I find that JavaScript's lack of distinction makes it far less useful than Visual Basic's variant, as the risk of ambiguity is too high. Other than that, with is still a powerful idea that can make for better readability.

提交回复
热议问题