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

后端 未结 30 1764
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:28

    I think the obvious use is as a shortcut. If you're e.g. initializing an object you simply save typing a lot of "ObjectName." Kind of like lisp's "with-slots" which lets you write

    (with-slots (foo bar) objectname
       "some code that accesses foo and bar"
    

    which is the same as writing

    "some code that accesses (slot-value objectname 'foo) and (slot-value objectname 'bar)""
    

    It's more obvious why this is a shortcut then when your language allows "Objectname.foo" but still.

提交回复
热议问题