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

jQuery函数调用失效:调用this.play启动play()函数报错求助

解决调用this.play()报错的问题

嘿,我帮你找到问题所在了!你调用this.play()时报错,核心原因是jQuery事件回调里的this指向不对——在$(document).on('keypress', function(evt) {...})这个函数里,this指向的是document对象,而不是你的类实例,自然找不到play()方法。

下面给你三种可行的解决办法,还有代码优化建议:

方法一:保存类实例引用到变量

在event_listeners()方法里先把当前类实例的this存到一个变量(比如self),然后在回调里用这个变量调用play():

event_listeners() {
  var result;
  // 保存类实例的引用,避免this指向丢失
  var self = this;
  $(document).on('keypress', function(evt) {
    if (evt.which == 49) { result = 1; }
    else if (evt.which == 50) { result = 2; }
    else if (evt.which == 51) { result = 3; }
    else if (evt.which == 52) { result = 4; }
    else if (evt.which == 53) { result = 5; }
    else if (evt.which == 54) { result = 6; }
    // 用self调用类里的play方法
    self.play(result);
  });
}

方法二:使用箭头函数

箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的类实例),所以可以直接在回调里用this.play():

event_listeners() {
  var result;
  $(document).on('keypress', (evt) => {
    if (evt.which == 49) { result = 1; }
    else if (evt.which == 50) { result = 2; }
    else if (evt.which == 51) { result = 3; }
    else if (evt.which == 52) { result = 4; }
    else if (evt.which == 53) { result = 5; }
    else if (evt.which == 54) { result = 6; }
    // 直接用this就能访问类实例的play方法
    this.play(result);
  });
}

方法三:用bind绑定this

通过bind()方法把回调函数的this强制绑定到类实例上:

event_listeners() {
  var result;
  $(document).on('keypress', function(evt) {
    if (evt.which == 49) { result = 1; }
    else if (evt.which == 50) { result = 2; }
    else if (evt.which == 51) { result = 3; }
    else if (evt.which == 52) { result = 4; }
    else if (evt.which == 53) { result = 5; }
    else if (evt.which == 54) { result = 6; }
    this.play(result);
  }.bind(this)); // 绑定this到当前类实例
}

额外优化:简化按键判断逻辑

你现在的一堆else if可以用对象映射来简化,代码会更整洁:

event_listeners() {
  // 建立按键码和结果的映射关系
  const keyResultMap = {
    49: 1,
    50: 2,
    51: 3,
    52: 4,
    53: 5,
    54: 6
  };
  
  var self = this; // 或者用箭头函数、bind,看你选哪种方法
  $(document).on('keypress', function(evt) {
    const result = keyResultMap[evt.which];
    // 如果是目标按键,才调用play方法
    if (result !== undefined) {
      self.play(result);
    }
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:45:14