一:普通函数、
function fn(){
console.log(this)
}
fn() //window
二:使用bind,apply,call
function fn(){
console.log(this)
}
fn() //window
//call
fn.call({a:10}) //{a:10}
//bind
const fn2=fn.bind({b:20})
fn2() //{b:20}
三:作为对象方法被调用
const xiaoming = {
name: '小明',
say() {
//this指向当前对象
console.log(this)
},
wait() {
setTimeout(function () {
//this指向window
console.log(this)
}, 1000)
}
}
xiaoming.say()
xiaoming.wait()
四:在class方法中被调用
class Person {
constructor(name) {
this.name = name
this.age = 20
}
say(){
//this指向将来创建的实例
console.log(this)
}
}
const student=new Person('小明')
student.say()
五:箭头函数
箭头函数中自身没有this,它的this指向上级的this
const xiaoming = {
name: '小明',
say() {
//this指向当前对象
console.log(this)
},
wait() {
setTimeout( () => {
//this指向当前对象
console.log(this)
}, 1000)
}
}
注:在各个场景中this取什么值是在函数执行的时候确定的,不是在函数定义的时候决定的