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(18, 'zs') var p2 = new Person(18, 'ww')
3. 对象方法调用,此时的this 指向 该方法所属的对象
var obj = { fn: function () { console.log(this); // obj } } obj.fn();
4. 通过事件绑定的方法, 此时 this指向 绑定事件的对象
<body>
<button id="btn">hh</button>
<script>
var oBtn = document.getElementById("btn");
oBtn.onclick = function() {
console.log(this); // btn
}
</script>
</body>
5. 定时器函数, 此时 this指向 window
setInterval(function () { console.log(this); // window }, 1000);
1