this的指向是函数调用的时候确定的,调用方式不同this指向也不同
| 调用方式 | this指向 |
|---|
| 普通函数调用 | windows |
| 构造函数调用 | 实例对象 原型对象里面的方法也指向实例对象 |
| 对象方法调用 | 该方法所属对象 |
| 事件绑定方法 | 绑定事件对象 |
| 定时器函数 | windows |
| 立即执行函数 | windows |
普通函数-->this指向windows
function fn() {
console.log('函数this指向'+this);
}
fn()
对象方法-->this指向对象fn
var fn = {
sayHi: function () {
console.log('对象方法的this:' + this);
}
}
fn.sayHi()
构造函数-->this指向这个实例
function Star() {
console.log(this);
}
var ldh = new Star();
绑定事件函数-->this指向btn
var btn = document.querySelector('button')
btn.onclick = function() {
console.log('this指向',this);
}
定时器函数-->this指向windows
setTimeout(() => {
console.log('定时器this指向',this);
}, 100);
立即执行函数-->this指向windows
(function() {
console.log('立即执行函数',this);
})()