Jump to content

Javascript With()


webmaster

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;

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...