为什么小程序中,setTimeout函数里面的this指向本身

生命周期是这样写的

onReady: function () {

setTimeout(function() {
    console.log(this)
},0)

}

然后打印的是函数本身

ƒ () {

  console.log(this);
}
阅读 3.1k
1 个回答

这么写var that = this;
然后用that。

onReady: function () {

var that = this;
setTimeout(function() {
    console.log(this);
    console.log(that);
},0)


}

this顾名思义就是指本身,在setTimeout是个回调函数,那么在其函数里log出的this当然是其函数本身了。that才是你的页面的this。
如果有帮助请点赞并采纳。

就评论附加

全局环境中,this会返回顶层对象。但是,Node 模块和 ES6 模块中,this返回的是当前模块。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏