JS 环境下的 this 指向于方法执行的上下文
上下文:上下级的代码定义关系
var user = {
fun1: function () {
console.log(this) // fun1 的上下文是 user 对象,this 就是 user 对象
},
fun2: () => {
console.log(this) // fun2 的上下文是 window 对象,this 就是 window 对象
}
}
function show () {
console.log(this) // 全局函数的上下文是 window,this 就是 window 对象
}
改变上下文的指向
- new 关键字:会构建新的上下文关系
箭头:不具有 this 指向,箭头函数中的 this 指向于上一级非箭头函数或对象的上下文
var User = function (name) {
this.name = name
// 构造函数中的 this 会指向于当前构造器对应的实例
console.log(this)
this.fun1 = function () {
console.log('func1', this)
}
this.fun2 = () => {
console.log('fun2', this)
}
}
User() // 如果直接执行构造函数,this 还是执行 window,相当于 window.User()
var u = new User('biu)
// this 指向当前构造函数 new 出来的实例对象 u
u.fun1() // this 执行 u
u.fun2() // this 执行 u
// u.fun1() 和 u.fun2() 的 this 指向结果一样,但二者的取值不一样
// u.fun1() 非箭头函数,this 指向方法的调用者对象 u
// u.fun2() 箭头函数,this 本来不指向方法调用者 u,而是指向 u 所属的环境上下文,
// 但是刚好 u 是通过 new User 的方式将整个 User 构造器函数的上下文指向了 User
// 实例 u,所以箭头函数的 this 也指向了 u
- 三个特殊方法:apply,call,bind 会改变上下文关系
注意:在 vue 中定义的方法,使用箭头函数时, vue 源码中,将 vue 实例对象的一级箭头函数通过 call 方法将 this 指向了 window