[学习笔记] this 的5个应用场景

本文详细探讨了JavaScript中this的关键应用场景,包括在普通函数、call/apply/bind方法、对象、箭头函数以及class中的用法。通过实例解析,帮助理解this的绑定规则及其在不同场景下的变化。

1. this 作用于普通函数使用

function fn() {
	console.log(this)   //this === window
}

2. this 作用于 call, apply, bind

这里也顺便写出 call, apply 和 bind 的用法和区别, 之前刚接触这3种方法的时候弄的有点懵

const obj = {
	num: 2
}
const arr = [1,2,3]

function AddTwo (a) {
	console.log(typeof this)   // object
	console.log(this)   // { num: 2}   对象的内容
	console.log(this.num + a) 
}
function SumNumbers ( a, b, c) {
	console.log(this)   // { num: 2} 对象的内容
	console.log(this.num + a + b + c)
}

//call 可以有多个参数,但第一个须是对象,且只能有一个,其余为函数(AddTwo)参数
AddTwo.call(obj, 4)   
//apply 和 call用法一致,但只能有两个参数,一个是对象, 一个是包含参数的数组
SumNumbers.apply(obj, arr)  
//个人理解为 将bindFunction 指向 AddTwo 函数,而执行bindFunction时只需将函数所需参数代入即可
var bindFunction = AddTwo.bind(obj)
bindFunction(2)   

3. this 作用于对象

const person = {
	name: '人',
	sayHi() {
		console.log(this)  // this===当前对象
	},
	wait() {
		setTimeout( function () {    
			console.log(this) //this === window 
		}, 3000)
	},
}
person.wait()
person.sayHi()

4. this 作用于箭头函数

const person = {
	name: '人',
	sayHi() {
		console.log(this)  // this===当前对象
	},
	wait() {
		//当this 作用于箭头函数时,this是指向离自身最近的一层作用域的值 
		setTimeout( () => {  
			console.log(this) //this === 当前对象
		}, 2000)
	}
}

person.wait()
person.sayHi()

5. this 作用于class

class Human {
	constructor(name) {
		this.name = name
	}
	sayHi() {
		console.log(this)  
	}
	
}

const lee = new Human('李')
lee.sayHi()   // this === lee 对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值