zoukankan      html  css  js  c++  java
  • JavaScript 中this与Dom中的注意

    对于下面这段代码:

    <script type='text/javascript'>
        function testThis()
        {
             console.log(this);
        }
    </script>
    <input type='button' id="testBtn" />

    第一种绑定事件的方式:

    document.getElementById('testBtn').addEventListener('click',testThis,false)

     这种绑定方式中的this 是: <input type='button' id="testBtn" /> 这个对象。

    第二种绑定事件的方式:

    document.getElementById('testBtn').addEventListener('click',function(){testThis();},false)

    这种绑定事件的方式中的 this是: window.

    究其原因是 this 只与调用者的上下文有关.

    在第一个例子中:是 testBtn来调用触发了 testThis 这个方法,此时this所处的上下文就是 testBtn这个对象.

    在第二个离职中:是 testBtn来触发了一个匿名函数,调用者是testBtn,此时testThis 的调用者是window, this所处的上下文就是 window对象,相当于执行了 window.testThis()这个方法.

    我们再改改,如下代码:

      <script type='text/javascript'>
          var test={
              testThis: function () {
                  console.log(this);
              }
          }
    </script>

    第一种绑定方式:

    document.getElementById('testBtn').addEventListener('click',test.testThis, false)

    第二种绑定方式:

    document.getElementById('testBtn').addEventListener('click', function () { test.testThis() }, false)

    此时的第一种绑定方式中 是 testBtn来调用触发了 test.testThis ( 就是调用了 test这个对象中的 testThis这个方法 ,而不是由 test这个对象来调用的) ,此时this所处的上下文就是 testBtn这个对象.

    此时的第二种绑定方式中 是 testBtn来触发了一个匿名函数,testThis的调用者是test这个对象,此时this所处的上下文就是 test 对象.

  • 相关阅读:
    Codeforces Round #592 (Div. 2)C. The Football Season(暴力,循环节)
    Educational Codeforces Round 72 (Rated for Div. 2)D. Coloring Edges(想法)
    扩展KMP
    poj 1699 Best Sequence(dfs)
    KMP(思路分析)
    poj 1950 Dessert(dfs)
    poj 3278 Catch That Cow(BFS)
    素数环(回溯)
    sort与qsort
    poj 1952 buy low buy lower(DP)
  • 原文地址:https://www.cnblogs.com/huaan011/p/6074704.html
Copyright © 2011-2022 走看看