this is this
this是我们常见的一种关键字,在不同的场景下this也代表不同的含义。一般地,我们把this分为5种情况:1.默认绑定。2.隐式绑定。3.显式绑定。4.new 关键字绑定。5.箭头函数。下面分别简单的介绍下各种情况以及最后的判断图。
- 默认绑定
function fn() {
console.log(this)
}
fn(); // this => window
PS:严格模式下
'use strict'
function fn() {
console.log(this)
}
fn(); // this => undefined
- 隐式绑定
let obj = {
a:1,
fn:fn
}
function fn() {
console.log(this)
}
obj.fn(); // this => obj
PS:有一个坑的情况
let obj = {
a:1,
myfn() {
return fn()
}
}
function fn() {
console.log(this)
}
obj.myfn(); // this => window
简单的理解就是因为函数的存储方式引用所导致的,具体请小伙伴们自信baidu咨询
- 显式绑定
let obj1 = {
a:1,
fn:fn
}
function fn() {
console.log(this)
}
let obj2 = {
b:2
}
obj1.fn.call(obj2); // this => obj2
// apply是一样的
- new 关键字绑定
function Fn() {
console.log(this)
}
let myfn = new Fn(); // this => Fn {} this指向新创建的对象
- 箭头函数
根据当前的词法作用域来决定this,箭头函数会继承外层函数调用的this绑定
下面直接上图
