this code in book jQuery in action page 99
Why he wrote this line
var current = this;
<!DOCTYPE html>
<html id="greatgreatgrandpa">
<head>
<title>DOM Level 0 Bubbling Example</title>
<link rel="stylesheet" type="text/css" href="../styles/core.css"/>
<script type="text/javascript" src="../scripts/jquery-1.4.js"></script>
<script type="text/javascript" src="../scripts/jqia2.support.js"></script>
<script type="text/javascript">
$( function() {
$('*').each( function() {
var current = this;
this.onclick = function(event) {
if (!event)
event = window.event;
var target = (event.target) ?
event.target : event.srcElement;
say('For ' + current.tagName + '#'+ current.id +
' target is ' +
target.tagName + '#' + target.id);
};
});
});
</script>
</head>
<body id="greatgrandpa">
<div id="grandpa">
<div id="pops">
<img id="example" src="example.jpg" alt="ooooh! ahhhh!"/>
</div>
</div>
</body>
</html>
He did that so that the
thisvalue could be preserved and used inside a nested lexical scope. Each function call to any function involves (internally) settingthisto refer to some object, based on the details of the invocation. Thus, inside a nested function (a function declared inside another function, as in this case), should there be a need to refer to the “outer” value ofthis, well, there’s a problem:this, in that nested context, will have been set to refer to something else (not necessarily, but possibly). By “capturing”thisin the outer context, that inner code will be able to refer to it freely.That’s a pretty good book by the way; I used to work with one of the authors (Bear) 🙂