1、普通函数
this指向window对象
function fn(){
console.log(this); // Window
}
fn()
2、对象中的方法
this指向该方法的所属对象
const obj = {
say:function(){
console.log(this); //{say: ƒ}
}
}
obj.say()
3、构造函数
this指向构造函数的实例化对象(原型上的方法同样如此)
function Person(){
Person.prototype.say = function(){
console.log(this); // Person {}
}
}
const hzy =new Person()
hzy.say()
4、绑定事件函数
this指向事件绑定的对象
const btn = document.querySelector('button');
btn.onclick = function(){
console.log(this); // <button>123</button>
}
5、定时器函数
this指向window对象
setTimeout(() => {
console.log(this); // // Window
}, 1000);
6、立即执行函数
this指向window对象
(function(){
console.log(this); // window
})()
7、箭头函数
箭头函数没有自己this指向,里面的this指向外层作用域(如果箭头函数外层有函数,那么外层函数的this就是箭头函数的this,如果没有,则this指向window)
//箭头函数外层没有函数
let sum = (x,y)=>{
console.log(this); //Window
return x + y;
}
sum(1,2)
//箭头函数外层有函数
const btn = document.querySelector('button');
btn.onclick = function () {
let sum = (x, y) => {
console.log(this); //this指向btn
return x + y;
}
sum(1, 2)
}
本文详细解析JavaScript中this的关键用法,涵盖普通函数中的window对象、对象方法的上下文、构造函数实例化、事件处理、定时器、立即执行函数和箭头函数的独特行为。理解this指向变化有助于提升代码可读性和可维护性。
2291

被折叠的 条评论
为什么被折叠?



