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

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

    Yes, yes and yes. There is a very legitimate use. Watch:

    with (document.getElementById("blah").style) {
        background = "black";
        color = "blue";
        border = "1px solid green";
    }
    

    Basically any other DOM or CSS hooks are fantastic uses of with. It's not like "CloneNode" will be undefined and go back to the global scope unless you went out of your way and decided to make it possible.

    Crockford's speed complaint is that a new context is created by with. Contexts are generally expensive. I agree. But if you just created a div and don't have some framework on hand for setting your css and need to set up 15 or so CSS properties by hand, then creating a context will probably be cheaper then variable creation and 15 dereferences:

    var element = document.createElement("div"),
        elementStyle = element.style;
    
    elementStyle.fontWeight = "bold";
    elementStyle.fontSize = "1.5em";
    elementStyle.color = "#55d";
    elementStyle.marginLeft = "2px";
    

    etc...

提交回复
热议问题