JS基础(八)--this 关键字用法详解

一、this关键字的使用方法

  1. 方法中的 this,指向调用方法的对象
  2. 全局环境下的 this ,指向全局对象
  3. 全局函数中的 this,指向全局对象
  4. 内部函数中的 this,指向全局对象
  5. 事件中的 this.指向触发事件的DOM对象
  6. 构造函数中的 this ,指向 new 创建的对象【面试题new 的作用】
  7. 箭头函数中的 this, 指向定义函数上下文的 this
  8. 使用 闭包, var 获取dom 的索引
<script>
/*
	1、直接输出 this 指向全局对象
*/
// this
console.log(this)  // window

// 全局函数其实是window (全局对象) 的方法
function fun(){
	console.log(this)
}
window.fun();

// this 放在方法中,this指向调用这个方法的对象
let cat = {
	name: "喵喵",
	sayName(){
		console.log("我是" + this.name)
	}
}

cat.sayName();
</script>
 <body>
 <button>按钮</button>
 
 <script>
	const btn = document.querySelector("button");
	btn.onclick = function(){
		console.log(this);
	}
</script>
 </body>
<script>
// new 关键字做了什么:new 会创建对象,将构造函数中的 this 指向创建出来的对象
//  构造函数:是用来创建对象
function F(){
	this.name = "小明";
	}
let f = new F();
console.log(f);

// 箭头函数没有 this
/*
	1、普通函数,谁调用谁指向谁,箭头函数:在哪里定义指向谁
	2、箭头函数外指向谁就指向谁
	3、箭头函数中没有 this

*/

let cat = {
	name: "喵喵",
	sayName(){
		setTimeout(()=>{
			console.log(this)
		},1000)
	}
}
cat.sayName();
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值