Jump to content

Javascript With()


webmaster
 Share

Recommended Posts

with is a shortcut for accessing the members of an object (including arrays) without naming the object. It is especially useful when you want to access a lot of members, since it cuts down on typing and makes the code more readable. Example:

my_object = {}; my_object.name = "Cindy"; my_object.color = "blond"; my_object.job = "florist"; my_object.age = 24; with (my_object) {	 str = name + " the " + color + " " + job + " is " + age;	 alert (str); }

If I hadn't used with, the string assignment line would have to look like this:

	str = my_object.name + " the " + my_object.color + " " + my_object.job + " is " + my_object.age;

Edited by Deirdre's Dad
Link to comment
Share on other sites

So with this example:

<html><head><script type="text/javascript">function validate_required(field,alerttxt){with (field)  {  if (value==null||value=="")	{	alert(alerttxt);return false;	}  else	{	return true;	}  }}function validate_form(thisform){with (thisform)  {  if (validate_required(email,"Email must be filled out!")==false)  {email.focus();return false;}  }}</script></head><body><form action="submit.htm" onsubmit="return validate_form(this)" method="post">Email: <input type="text" name="email" size="30"><input type="submit" value="Submit"></form></body></html>

, there really is no object, and there is an if statement within with. Can someone explain to me why the with() statement is used here?

Link to comment
Share on other sites

If Javascript finds an undefined variable inside a with block, it will check to see if the object contains a property with the same name. The first if statement checks a variable called value, if there's no defined variable called value then it looks for field.value instead.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...