this指向问题

56 阅读1分钟

1.普通函数调用,此时 this 指向 window

    function fn() {
       console.log(this);   // window
     }
     fn();  //  window.fn(),此处默认省略window

2.构造函数调用, 此时 this 指向 实例对象

 function Person(age, name) {
         this.age = age;
         this.name = name
         console.log(this)  // 此处 this 分别指向 Person 的实例对象 p1 p2
     }
    var p1 = new Person(15, 'lang')
    var p2 = new Person(20, 'ge')

3.对象方法调用, 此时 this 指向 该方法所属的对象

 var obj = {
       fn () {
         console.log(this); // obj
       }
     }
    obj.fn();//对象调用里面的方法

4.dom事件调用this指向绑定的dom


<body>
    <button id="btn">默认按钮</button>
</body>
<script>
    var oBtn = document.getElementById("btn");
    oBtn.onclick = function() {
        console.log(this); // dom事件调用this指向绑定的dom  //<button id="btn">默认按钮</button>
    }
</script>

5.定时器函数, 此时 this 指向 window

 setInterval(function () {
       console.log(this); // window
     }, 1000);