当函数被不同地调用时,'this'的值

时间:2011-10-05 22:13:01

标签: javascript

在此页面上:https://developer.mozilla.org/en/DOM/element.addEventListener

警告在使用this时调用modifyText()函数时addEventListener()的值会有所不同,而不是直接在HTML中使用onclick=''应用事件。在上面链接的页面中,请注意第一个示例(实际上是第二个示例),然后是以下标题为“处理程序中this的值”的部分。

我决定测试一下,但找不到区别。我做错了什么?

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>

2 个答案:

答案 0 :(得分:2)

在addEventListener示例中,您将modifyText包装在另一个函数中。所有this魔法都会发生在外部函数上,而modifyText将不会看到任何外部函数。

尝试将modifyText直接传递给addEventListener

node.addEventListener('click', modifyText);
//and make sure to change modifyText to receive no parameters or it wont work :) 

如果您仍然希望能够选择参数,请使用闭包功能:

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')()

答案 1 :(得分:0)

这是对存储函数的对象的引用。 所以在你的例子中,这指的是窗口全局对象。

试验:

t2.innerHTML = new_text + '<br />this: <b>' + (this === window) + '</b>';

会写真