this关键字指向问题
1.对象方法里的this,指向调用方法的对象
2.事件中的this指向触发事件的DOM对象
3.构造函数中的this指向new创建的对象(new关键字做了什么?)
new会创建一个对象,并将构造函数中的this指向创建中的对象
4.箭头函数中没有this(箭头函数外指向谁,箭头函数里的this指向谁)
function Fn(){
this.name='miaomiao'
this.sayHi=function(){
// this指向fn
console.log(this);
setTimeout(()=>{
//this指向fn
console.log(this);
}
,1000)
}
}
let fn=new Fn()
fn.sayHi()
5.计时器中的this指向window(计时器函数为全局函数,全局函数中的this指向window)
function Fn(){
this.name='miaomiao'
this.sayHi=function(){
// this指向fn
console.log(this);
setTimeout(function(){
//this指向window
console.log(this);
},1000)
}
}
let fn=new Fn()
fn.sayHi()

本文来自博客园,作者:Kira的学习笔记,转载请注明原文链接:https://www.cnblogs.com/kira2022/p/16105641.html

浙公网安备 33010602011771号