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

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

    I think that the usefulness of with can be dependent on how well your code is written. For example, if you're writing code that appears like this:

    var sHeader = object.data.header.toString();
    var sContent = object.data.content.toString();
    var sFooter = object.data.footer.toString();
    

    then you could argue that with will improve the readability of the code by doing this:

    var sHeader = null, sContent = null, sFooter = null;
    with(object.data) {
        sHeader = header.toString();
        sContent = content.toString();
        sFooter = content.toString();
    }
    

    Conversely, it could be argued that you're violating the Law of Demeter, but, then again, maybe not. I digress =).

    Above all else, know that Douglas Crockford recommends not using with. I urge you to check out his blog post regarding with and its alternatives here.

提交回复
热议问题