JavaScript this 关键字的理解
仅供个人学习做笔记使用,大佬轻喷
1. 全局环境直接输出this指向全局对象
console.log(this)
2. 全局函数输出this指向window
全局函数其实是window(全局对象)的方法
function fun {
console.log(this);
}
fun();//等价 window.fun()
3.对象的方法输出this
this放在方法中,this 指向调用这个方法的对象
let cat = {
name="喵喵",
sayName(){
console.log("我是"+this.name)
}
}
cat.sayName();//我是喵喵
4.箭头函数中的this
对于箭头函数的理解以下均是正确的:
- 箭头函数中没有this。
- 普通函数,谁调用指向谁。箭头函数,在哪里定义指向谁。
- 箭头函数外指向谁就指向谁。
let cat = {
name:"喵喵",
sayName(){
setTimeout(function(){
console.log(this}
},1000)
}
}
cat.sayName();//打印 window对象
let cat = {
name:"喵喵",
sayName(){
setTimeout(()=>{
console.log(this)
},1000)
}
}
cat.sayName();//打印 cat对象