JavaScript this关键字的理解

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

对于箭头函数的理解以下均是正确的:

  1. 箭头函数中没有this。
  2. 普通函数,谁调用指向谁。箭头函数,在哪里定义指向谁。
  3. 箭头函数外指向谁就指向谁。
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对象

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43316970/article/details/123982793