01_13.箭头函数的this应用

2017-11-13  本文已影响0人  Robyn_Luo
<script>
    function Tab() {
        this.btn = document;
        this.target = document.body;
    }

    Tab.prototype = {

        // 给btn绑定事件
        bind: function() {
          console.log(this);  // this为tab实例
          this.btn.onclick = () => {
            console.log(this); // this为上级的tab实例,不再是元素
          };
        },

        fn: function() {
            
           // 使用箭头函数,回调里面的this就指向了上级的tab实例
           // 相比以前我们不用再通过一个临时变量存储外界this值了,比如var that = this;
           setTimeout(() => {
              console.log(this);
           }, 1000);

        }
    };

    var tab = new Tab();
    tab.bind();
    tab.fn();
    </script>
上一篇 下一篇

猜你喜欢

热点阅读