0

I seeing a java script function on web page which used with() at the top of function and rest of function implementation doing within with() statement. I put the function code below for reference.

function calculate()
{
     with (document.loan)
    {
      var loan = parseFloat(loan_amount.value);
      //function implementation goes here
    }
}

Form is define like this in page with name of loan.

<form name="loan" id="loan-form">
   <input type="text" id="loan_amount"/>
  // remaining form elements here
</form>

What is doing this "with" statement and what's it scope ?

Ahmar
  • 3,717
  • 2
  • 24
  • 42
  • possible duplicate of [Are there legitimate uses for JavaScript's "with" statement?](http://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement) – Rob Hruska May 07 '13 at 01:52
  • Also useful: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with – Rob Hruska May 07 '13 at 01:53
  • This question: http://stackoverflow.com/q/61552/1846192 and this answer: http://stackoverflow.com/a/185283/1846192 will be of interest to you. – Mathijs Flietstra May 07 '13 at 01:53

1 Answers1

2

JavaScript’s with statement was intended to provide a shorthand for writing recurring accesses to objects.

So instead of writing

myObj.obj2.obj3.bing = true;
myObj.obj2.obj3.bang = true;

You can write

with (myObj.obj2.obj3) {
    bing = true;
    bang = true;
}
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • But you probably shouldn't per http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/ – jarmod May 07 '13 at 02:04