this的取值是在函数执行时决定的,而不是在函数定义时!!!
// 第一种 : 作为普通函数
const fn(){
console.log(this)
}
fn() // 输出的是window
// 第二种 : 通过call apply bind
const fn(){
console.log(this)
}
fn.call({x : 100}) // .apply({x : 100})
fn() // 输出的是{x : 100}
// 使用.bind会返回一个新的方法
const fn1 = fn.bind({x : 200})
fn1() // 输出 {x : 200}
// 第三种 : 作为对象方法
const zhangsan = {
name : '张三',
showThis : function(){
console.log(this) // 对象本身
},
timeout : function(){
setTimeout(function(){
console.log(this) // this指向window 所以在这里并不能优雅的使用this.showThis
})
}
}
// 第四种 : 箭头函数
const zhangsan = {
name : '张三',
showThis : function(){
console.log(this) // 对象本身
},
timeout : function(){
// 箭头函数会改变this指向,指向上级作用域的this
setTimeout(() => {
this.showThis() // this指向对象本身 所以在这里可以非常低调且不失优雅的使用this.showThis
})
}
}
// 第五种 : class
class people{
constructor (name,age) {
this.name = name
this.age = age
}
showThis(){
console.log(this)
}
}
var zhangsan = new people('张三','26')
zhangsan.showThis() // 指向当前class实例化出来的对象本身 即 张三