//1.普通函数调用,this指向window
function fn() {
console.log(this); // window
}
fn()
//2.构造函数调用,this指向实例对象
function Person(age,name) {
this.age = age
this.name = name
console.log(this) //Person
}
new Person(18,"李华")
//3.对象方法调用,this指向该方法所属的对象
let obj = {
name:"李华",
fn: function () {
console.log(this); // obj
}
}
obj.fn();
//4.通过事件绑定的方法,this指向绑定事件的对象
let btn = document.querySelector('button')
btn.onclick = function () {
console.log(this) //<button>1</button>
}
//5.定时器函数,this指向window
setTimeout(function () {
console.log(this); //window
},500)
//6.更改this指向的三个方法
call(),apply(),bind()