1.普通函数中
- 非严格模式下:this -> window
function fn() {
console.log(this) // window
}
fn()
- 严格模式下:this ->undefined
'use strict'
function fn() {
console.log(this) // undefined
}
fn()
2.call、apply、bind中
这里以call为例
- 调用时啥也不传(包括 null、undefined):this -> window
function fn() {
console.log(this)
}
fn.call() // window
fn.call(null) // window
fn.call(undefined) // window
- 传入什么,this就是什么
function fn() {
console.log(this)
}
fn.call(123) // {1,2,3}
fn.call({ age: 22 }) // {age: 22}
3.定时器中
- 定时器 + function:this -> window
setTimeout(function () {
console.log(this) // window
}, 100)
- 定时器 + 箭头函数:this -> 上层作用域的this
class Obj {
fn(){
setTimeout(() => {
console.log(this);
}, 100);
}
}
let obj1 = new Obj();
obj1.fn() // Obj
4. 箭头函数
- 有 function 作用域:this是上层作用域的this
class Obj {
fn = () => {
console.log(this)
}
}
let obj1 = new Obj()
obj1.fn() // Obj
- 没有 function 作用域:this -> window
let obj = {
fn: () => {
console.log(this)
}
}
obj.fn() // window
今日寄语:生以悦己,非困于人!