I still find the with
keyword a bit...enigmatic.
Briefly, with
behaves like this:
with (obj) {
// do stuff
}
This adds obj
to the head of the scope chain and then executes the with-block. When the block is finished it removes obj
from the head of the scope chain.
According to MDC, this allows you to do stuff like
var a, x;
var r = 10;
with(Math) {
a = PI * r * r;
x = r * cos(PI / 2);
}
So I can reference properties of Math
-- like PI
-- directly, without saying Math.PI
. Which is fine, but kind of useless.
Can anyone provide an example of an interesting usage of with
?
An alternative to the standard closure solution using functions inside of a for loop:
<a href="#">blah</a><br>
<a href="#">blah</a><br>
<a href="#">foo</a><br>
<script>
(function() {
var anchors = document.getElementsByTagName('a');
for ( var i = anchors.length; i--; ) {
var link = anchors[i];
with ({ number: i }) {
link.onclick = function() {
alert(number);
};
}
}
})();
</script>
Credit to nlogax
for providing a solution which I pretty much ripped off:
Javascript infamous Loop issue?
Here's the standard solution:
<script>
(function() {
var anchors = document.getElementsByTagName('a');
for ( var i = anchors.length; i--; ) {
var link = anchors[i];
(function(i) {
link.onclick = function() {
alert(i)
}
})(i);
}
})();
</script>