You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript类中如何从事件监听器回调调用成员函数

如何在类成员函数的回调中调用类的成员方法

你遇到的Uncaught TypeError: this.finished is not a function错误,核心原因是setTimeout的回调函数内部的this并不指向C类的实例,而是指向全局对象(浏览器环境下为window,严格模式下为undefined),所以无法找到finished方法。以下是几种可行的解决方式:

  • 使用箭头函数
    箭头函数不会绑定自身的this,它会继承外层作用域(也就是timer方法)的this,自然指向C类的实例:

    class C {
      finished() {
        console.log('over');
      }
      
      timer() {
        console.log('started')
        setTimeout(() => {
            this.finished();
        }, 500);
      }
    }
    
    let c = new C();
    c.timer();
    
  • 提前保存实例的this到变量
    在timer方法里先把指向实例的this存到一个变量(比如that),回调函数里直接使用这个变量访问实例方法:

    class C {
      finished() {
        console.log('over');
      }
      
      timer() {
        console.log('started')
        const that = this;
        setTimeout(function fct() {
            that.finished();
        }, 500);
      }
    }
    
    let c = new C();
    c.timer();
    
  • 用bind方法绑定this
    通过bind方法把回调函数的this强制绑定到当前类实例:

    class C {
      finished() {
        console.log('over');
      }
      
      timer() {
        console.log('started')
        setTimeout(function fct() {
            this.finished();
        }.bind(this), 500);
      }
    }
    
    let c = new C();
    c.timer();
    

内容的提问来源于stack exchange,提问作者Fifi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:22:09