1.普通函数调用,此时 this 指向 window
function fn() {
console.log(this);
}
fn();
2.构造函数调用, 此时 this 指向 实例对象
function Person(age, name) {
this.age = age;
this.name = name
console.log(this)
}
var p1 = new Person(15, 'lang')
var p2 = new Person(20, 'ge')
3.对象方法调用, 此时 this 指向 该方法所属的对象
var obj = {
fn () {
console.log(this);
}
}
obj.fn();
4.dom事件调用this指向绑定的dom
<body>
<button id="btn">默认按钮</button>
</body>
<script>
var oBtn = document.getElementById("btn");
oBtn.onclick = function() {
console.log(this);
}
</script>
5.定时器函数, 此时 this 指向 window
setInterval(function () {
console.log(this);
}, 1000);