Using WITH(...) in JavaScript

Some days ago I had a look in some Visual Basic source code and found the WITH statement there. I was thinking about how I can use this in JavaScript code. Below you will find a very simple script that allows you to use the With method (that will reduce your source code size of JavaScript files):

<html><body>

<style>
.myclassname {font-family:arial;}
</style>

<div id="test">My dummy text.</div>

<script type="text/javascript">

function With(o, p) {
  for(var prop in p) {
    o[prop] = p[prop];
  }
}

var ele = document.getElementById("test");

With(ele.style, {
  color:"red",
  fontSize:"12px",
  backgroundColor:"yellow"
});

With(ele, {
  className:"myclassname"
});

</script>

</body></html>

Published Friday, November 11, 2005 12:04 AM by Michael Schwarz

Comments

# re: Using WITH(...) in JavaScript

Thursday, November 10, 2005 6:32 PM by Ron Buckton
javascript already supports with(o) {...}

with in js temporarily changes the global object to the specified object passed as a param to the with statement.

Only predefined properties and expandos can be set in this way. If the object does not define the expando it will not create one:

with(el.style)
{
color = "black";
}

# re: Using WITH(...) in JavaScript

Thursday, November 10, 2005 6:38 PM by Michael Schwarz
You are talking about the "with" statement of JavaScript, yes, there you can only set properties that are predefined. The new "With" function will set any property you specify, that is the difference.