如何理解this关键字
1. 全局环境下,this指向全局对象
console.log(this);
输出:
2. 全局函数中的this,指向全局对象
function fun() {
console.log("我是函数一");
console.log(this);
}
fun();
输出:
3. 事件中的this,指向触发事件的DOM对象
const btn = document.querySelector("button");
btn.onclick = function() {
console.log(this);
}
输出:
4. 构造函数中的this,指向new创建的对象
function F() {
this.name = "小明";
}
let f = new F();
console.log(f);
输出:
new关键字的作用:new会创建对象,将构造函数中的this指向创建出来的对象。
5. 箭头函数中的this,指向定义函数上下文的this
let cat = {
name: "喵喵喵",
sayName() {
console.log("1", this)
setTimeout(function() {
console.log("2", this)
}, 1000)
}
}
cat.sayName();
输出:
let cat = {
name: "喵喵喵",
sayName() {
console.log("1", this)
setTimeout(() => {
console.log("2", this)
}, 1000)
}
}
cat.sayName();
输出:
第一个定时器函数是一个全局函数所以指向全局对象,改为箭头函数后指向对象。箭头函数在哪里定义就指向谁。