On this page: https://developer.mozilla.org/en/DOM/element.addEventListener
It is warned that the value of this
will be different when calling the modifyText()
function when using addEventListener()
as opposed to applying the event using onclick=''
directly in the HTML. In the page linked above, note the first example (actually it's the second), and then the following section titled 'The value of this
within the handler'.
I decided to test this, but cannot find a difference. What am I doing wrong?
addeventlistener2.html:
<html>
<head>
<title>DOM Event Example 1</title>
<style type="text/css">
#t { border: 1px solid red }
#t1 { background-color: pink; }
</style>
<script type="text/javascript">
// Function to change the content of t2
function modifyText(new_text) {
var t2 = document.getElementById("t2");
t2.innerHTML = new_text + '<br />this: <b>' + this + '</b>';
}
// Function to add event listener to t
function load() {
var el = document.getElementById("t");
el.addEventListener("click", function(){modifyText("body onload")}, false);
}
</script>
</head>
<body onload="load();">
<p>has onload in body.开发者_运维问答</p>
<table id="t">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
</body>
</html>
addeventlistener2.html:
<html>
<head>
<title>DOM Event Example 2</title>
<style type="text/css">
#t { border: 1px solid red }
#t1 { background-color: pink; }
</style>
<script type="text/javascript">
// Function to change the content of t2
function modifyText(new_text) {
var t2 = document.getElementById("t2");
t2.innerHTML = new_text + '<br />this: <b>' + this + '</b>';
}
</script>
</head>
<body>
<p>has onclick in table:</p>
<table id="t" onclick='modifyText("boo!")'>
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
</body>
</html>
In the addEventListener example you are wrapping modifyText inside an other function. All the this
magic will happen to that outer function and modifyText won't see any of it.
Try passing modifyText directly to addEventListener
node.addEventListener('click', modifyText);
//and make sure to change modifyText to receive no parameters or it wont work :)
Or use the power of closures if you still want to be able to choose the parameter:
function modifyText(new_text) {
return function(){
var t2 = document.getElementById("t2");
t2.innerHTML = new_text + '<br />this: <b>' + this + '</b>';
};
}
//addEventListener(modifyText('txt'))
//versus
//onclick=modifyText('txt')()
Hej this referce to the object witch the function is stored. so in both your examples this refers to window the global object.
test:
t2.innerHTML = new_text + '<br />this: <b>' + (this === window) + '</b>';
will write true
精彩评论