this的指向有哪几种?
①对象的方法---指的是谁,被哪个对象调用就是谁。
let obj = {
a: 1,
run() {
console.log(this.a);
console.log(this);
}
}
// run 里面的this 就是 obj
obj.run();
// 在函数执行的时候确定的
let fn = obj.run;
//fn 全局函数--this -window
fn();
②构造函数内部---new +构造函数
---创建对象, 构造函数内部的this 就是指new的时候创建的对象。
function Movie(name) {
this.name = name
console.log(this);
}
let m1 = new Movie('奇迹');
console.log(m1);
③事件处理函数---给谁添加的事件 ,事件处理函数中this就是谁。
btn.onclick = function(){} btn.addEventListenr('click',function(){}
document.onclick = function () {
console.log(this);//document
}
document.addEventListener('click', function () {
console.log(this);
})
④普通全局函数---(没有归属---看不出被谁调用---属于谁)匿名函数 ---window
function test() {
// Window
console.log(this);
}
test();
setTimeout(function () {
// Window
console.log(this);
}, 1000);
let arr = [1, 2, 3];
arr.forEach(function () {
// Window
console.log(this);
})
⑤箭头函数--- 没有自己的this,跟上下文一致。
document.addEventListener('click', function () {
console.log(this);//document
setTimeout(() => {
console.log(this);//document
}, 1000);
})