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>
2 Comments
Comments have been disabled for this content.
Ron Buckton said
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";
}
Michael Schwarz said
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.