首先注意一点:this取什么值是在函数执行的时候被确定的,不是在定义的时候被确定的【非常重要】
下面是5种赋值情况,大家可以再自己电脑上写一写打印出来看看
1.作为普通函数被调用
function fn(){
console.log(this) // window
}
fn() // window
2.作为对象方法被调用
const zhangsan = {
name:'张三',
sayHi(){
console.log(this) // this是zhangsan这个对象,因为是zhangsan.sayHi()被执行
},
wait(){
setTimeout(function(){
console.log(window) //this===window 因为setTimeOut之后当这个方法被执行时候,就是再window下面执行的
})
},
waitAgain(){
setTimeOut(()=>{
console.log(this) // zhangsan 箭头函数的this指向上级作用域的this
})
}
}
3.再class方法中被调用
class People{
constructor(){
this.name = name; // this 创建的实例
this.age = 20;
}
sayHi(){ console.log(this) } // this就是zhangsan这个实例
}
const zhangsan = new People('zhangsan')
zhangsan.sayHi() // zhangsan对象
4.箭头函数
箭头函数的this指向上级作用域的this
5.使用call apply bind 被调用
fn1.call({x:100}) // this是{x:100} 调用的对象
const fn2 = fn1.bind( {x:200})
fn2() // this 是 {x:200} 调用的对象
下面我们先来看几个函数调用的场景
function foo() {
console.log(this.a)
}
var a = 1
foo() // 1 window.a =1
const obj = {
a: 2,
foo: foo
}
obj.foo() // 2 obj.a=2
const c = new foo() //undefined
接下来我们一个个分析上面几个场景
- 【1】对于
直接调用 foo来说,不管foo函数被放在了什么地方,this一定是window - 【2】对于
obj.foo()来说,谁调用了函数,谁就是this, - 【3】对于
new的方式来说,this被永远绑定在了c【实例】上面,不会被任何方式改变this
说完了以上几种情况,其实很多代码中的 this 应该就没什么问题了,下面让我们看看箭头函数中的 this
a = function () {
return () => {
return () => {
console.log(this)
}
}
}
console.log(a()()())
- 【4】箭头函数其实是没有
this的,箭头函数中的this只取决包裹箭头函数的第一个普通函数的this。
在这个例子中,因为包裹箭头函数的第一个普通函数是 a,所以此时的 this 是 window。另外对箭头函数使用 bind 这类函数是无效的。
- 【5】最后种情况也就是
bind这些改变上下文的 API 了,对于这些函数来说,this取决于第一个参数,如果第一个参数为空,那么就是window。 那么说到bind,不知道大家是否考虑过,如果对一个函数进行多次bind,那么上下文会是什么呢?
let a = {}
let fn = function () { console.log(this) }
fn.bind().bind(a)() // => ?
如果你认为输出结果是 a,那么你就错了,其实我们可以把上述代码转换成另一种形式
// fn.bind().bind(a) 等于
let fn2 = function fn1() {
return function() {
return fn.apply() // 第一步
}.apply(a) // 第二步
}
fn2()
可以从上述代码中发现,不管我们给函数 bind 几次,fn 中的 this 永远由第一次 bind 决定,所以结果永远是 window。
let a = { name: 'yck' }
function foo() {
console.log(this.name)
}
foo.bind(a)() // => 'yck'
以上就是 this 的规则了,但是可能会发生多个规则同时出现的情况,这时候不同的规则之间会根据优先级最高的来决定 this 最终指向哪里。
首先,new 的方式优先级最高,接下来是 bind 这些函数,然后是 obj.foo() 这种调用方式,最后是 foo 这种调用方式,同时,箭头函数的 this 一旦被绑定,就不会再被任何方式所改变。
如果你还是觉得有点绕,那么就看以下的这张流程图吧,图中的流程只针对于单个规则。
流程图
总结
1.普通函数直接调用,就是window
2.谁调用就是谁; 作为对象方法被调用
3.new的话就是实例
4.箭头函数就是上一级this
5.call、apply、bind永远是第一次传的参数决定