What does “with” do in JavaScript?

前端 未结 8 1666
北荒
北荒 2020-12-28 18:06

I saw JavaScript code which begins with with. That\'s a bit confusing. What does it do and how can it be used correctly?

with (sObj) return opti         


        
8条回答
  •  爱一瞬间的悲伤
    2020-12-28 18:22

    Your example could be rewritten as...

    return sObj.options[selectedIndex].value;
    

    ...as the 'with' statement places all related statements in the scope of the supplied object. In this case, it's pretty pointless but, if you were doing lots of operations on 'sObj', then it saves a lot of typing.

    Totally ficticious example..

    with (sObj) 
    {
       if(options[selectedIndex].value < 10){
           options[selectedIndex].value++;
           total+ = options[selectedIndex].value;
       }
    }
    

    But, having said that, it's often the case that saving typing can be achieved in better ways.

提交回复
热议问题