绑定' this'在JavaScript函数中

发布于 2025-01-27 03:48:41 字数 840 浏览 2 评论 0原文

我有一个函数:

 interval(duration, fn) {
  var _this = this
  this.baseline = undefined
  
  this.run = function(){
    if(_this.baseline === undefined){
      _this.baseline = new Date().getTime()
    }
    fn()
    var end = new Date().getTime()
    _this.baseline += duration

    var nextTick = duration - (end - _this.baseline)
    if(nextTick<0){
      nextTick = 0
    }
    
    _this.timer = setTimeout(function(){
      _this.run(end)
    }, nextTick)
  }

  this.stop = function(){
    clearTimeout(_this.timer)
  }
}

现在,当我这样调用此功能时:

var timer = new this.interval(this.tempo, function(){
        this.audio.pause()
        this.playBackground()
      })

我需要以某种方式绑定“ this”,以便可以访问它,以便我可以调用this.audio.pause.pape()

如何绑定this我可以访问它吗?

I have a function:

 interval(duration, fn) {
  var _this = this
  this.baseline = undefined
  
  this.run = function(){
    if(_this.baseline === undefined){
      _this.baseline = new Date().getTime()
    }
    fn()
    var end = new Date().getTime()
    _this.baseline += duration

    var nextTick = duration - (end - _this.baseline)
    if(nextTick<0){
      nextTick = 0
    }
    
    _this.timer = setTimeout(function(){
      _this.run(end)
    }, nextTick)
  }

  this.stop = function(){
    clearTimeout(_this.timer)
  }
}

Now when I invoke this function as such:

var timer = new this.interval(this.tempo, function(){
        this.audio.pause()
        this.playBackground()
      })

I need to somehow bind 'this' so that it is accessible so that I can call on this.audio.pause()

How do I bind this so I can access it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文