6、this关键字

1、this关键字

  • 它是一个引用,指向内存中的一个对象

2、对象this的指向

this的指向类型
1、指向调用方法的对象最常用的一种情况,一个对象调用一个方法,那么方法中的this,指向这个对象
2、指向new创建出来的对象构造函数中的this,指向new创建出来的对象
	<script>
		// ES5的语法
		// 1、指向调用方法的对象
		let person = {
			name: "jasmine",
			getName() { console.log(this.name); }
		}
		person.getName();		// 输出结果:jasmine


		// 2、指向new创建出来的对象
		function person1(name) {
			this.name = name;
		}
		let person2 = new person1("jasmine");
		console.log(person2.name);		// 输出结果:jasmine


		// ES6的语法
		class Person3 {
			constructor(name) {
				this.name = name;
			}
		}
		let person4 = new Person3("jamsine");
		console.log(person4.name);		// 输出结果:jasmine
	</script>

3、DOM事件this的指向

  • 当DOM事件被触发时,事件监听函数中的this指向触发事件的DOM对象
	<button>按钮</button>
	<script>
		document.querySelector('button').onclick = function () {
			console.log(this);
		}
	</script>

4、全局事件this的指向

		// 2、全局函数this指向window
		function fun() { console.log(this); };
		fun();			// 输出结果:Window 

5、普通函数与箭头函数this的指向

类型this指向
普通函数指向window
箭头函数指向定义函数的上下文的this
		let person = {
			name: "jasmine",
			getName() { console.log(this.name); },
			getName1() {
				setTimeout(() => {
					// 箭头函数this指向对象
					console.log(`箭头函数:${this}`);
				}, 1000)
			},
			getName2() {
				setTimeout(function () {
					console.log(`普通函数:${this}`);
				}, 1000)
			}
		}
		person.getName();		// 输出结果:jasmine
		person.getName1();		// 输出结果:[object Object]
		person.getName2();		// 输出结果:[object Window]

总结

this关键字指向
1、全局环境下的this指向全局对象(Window)
2、全局函数中的this指向全局对象(Window)
3、内部函数中的this指向全局对象(Window)
4、方法中的this指向调用方法的对象
5、事件中的this指向触发事件的DOM对象
6、构造函数中的this指向new创建的对象
7、箭头函数中的this指向定义函数的上下文的this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jasmine_qiqi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值