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

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

    I think the object literal use is interesting, like a drop-in replacement for using a closure

    for(var i = nodes.length; i--;)
    {
           // info is namespaced in a closure the click handler can access!
           (function(info)
           {           
                nodes[i].onclick = function(){ showStuff(info) };
           })(data[i]);
    }
    

    or the with statement equivilent of a closure

    for(var i = nodes.length; i--;)
    {
           // info is namespaced in a closure the click handler can access!
           with({info: data[i]})
           {           
                nodes[i].onclick = function(){ showStuff(info) };
           }        
    }
    

    I think the real risk is accidently minipulating variables that are not part of the with statement, which is why I like the object literal being passed into with, you can see exactly what it will be in the added context in the code.

提交回复
热议问题