浏览器和nodejs中setTimeout中的this指向问题

// 全局 this 指向 global
// setTimeout this是 {}

1
2
3
// 浏览器:Window   node: Timeout
// strict: 浏览器:Window node: Timeout
setTimeout(function () { console.log(2, this) }, 0)
1
2
3
// 浏览器:Window   node: {}
// strict: 浏览器:Window node: {}
setTimeout(() => { console.log(3, this) }, 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
;(function () {
// 浏览器:Window node: global
// strict: 浏览器:undefined node: undefined
console.log(1, this)

// 浏览器:Window node: Timeout
// strict: 浏览器:Window node: Timeout
setTimeout(function () { console.log(4, this) })

// 浏览器:Window node: global
// strict: 浏览器:undefined node: undefined
setTimeout(() => { console.log(5, this) })
})()