使用场景
作为普通函数
使用call apply bind
作为对象方法被调用
箭头函数
在class方法在中被调用
this取什么值是在函数执行的时候确定的,不是在函数定义的时候确定的
function fn1() {
console.log(this)
}
fn1()//window
fn1.call({x:100})//{x:100}
const fn2 = fn1.bind({X:200})
fn2()//{x:200}
const zhangsan ={
name: '张三',
sayHi() {
//this即当前对象
console.log(this)
},
wait() {
setTimeout(function() {
//this === window
console.log(this)
});
}
}
箭头函数取值取上级作用域的值
const zhangsan ={
name: '张三',
sayHi() {
//this即当前对象
console.log(this)
},
wait() {
setTimeout(() => {
//this即当前对象
console.log(this)
});
}
}
class People {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(this)
}
}
const zhangsan = new People('张三');
zhangsan.sayHi();//zhangsan对象
本文详细探讨了JavaScript中this的取值情况,包括在普通函数、call/apply/bind的使用、对象方法、箭头函数以及在class方法中的应用。重点阐述了this的确定时机以及不同场景下的变化,帮助读者理解JavaScript中this的动态特性。
170万+

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



