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

被折叠的 条评论
为什么被折叠?



