JavaScript: setTimeout & setInterval

 

let i = 0
setTimeout(function (n) {
  console.log(55, n)
}, 1000, setTimeout(function () {
  console.log(44, i)
  i++
  return i+2
}))

 

 

先计算第三参数, 返回值为Timeout对象, 传递给第一参数, 浏览器中返回window

 

复制代码
const obj = {
  a: function () {
    console.log(this)
    setTimeout(function () {
      console.log(this)
    }, 1000)
  }
}

// obj.a()

let b = obj.a
b()
复制代码

Node:

 

 

Browser:

 

 

Node中指向Timeout对象, Browser中指向全局window

 

复制代码
const obj = {
  a: function () {
    console.log(this)
    setTimeout(function () {
      console.log(this)
    }, 1000)
  }
}

obj.a()
复制代码

 

Node:

 

 Browser:

 

 

 

Arrow Function

const obj = {
  a: function () {
    console.log(this)
    setTimeout(() => { console.log(this) }, 1000)
  }
}

obj.a()

 

一致

 

 

复制代码
const obj = {
  a: function () {
    console.log(this)
    setTimeout(() => { console.log(this) }, 1000)
  }
}

let b = obj.a
b()
复制代码

Node

 

 Browser

 

 

当b执行时, this才确定, setTimeout的arrow function绑定刚确定的this

posted @   ascertain  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示