Ahmar
Ahmar

Reputation: 3867

purpose of with() in javascript function

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 ?

Upvotes: 0

Views: 56

Answers (1)

Sachin
Sachin

Reputation: 40970

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;
}

Upvotes: 2

Related Questions