【问题标题】:TypeError: Cannot read property 'stimulus' of undefinedTypeError:无法读取未定义的属性“刺激”
【发布时间】:2021-08-31 07:32:40
【问题描述】:

我有一个显示图片幻灯片的程序。当图片显示在屏幕上时,我已将this 登录到控制台。因此,我们将this 对象打印到控制台:Photo of entire this object printed to console

我想访问stimulus 属性并将其打印到控制台,但是当我尝试console.log(this.stimulus) 时,我得到TypeError: Cannot read property stimulus of undefined。为什么我无法访问此属性?

编辑:忘记添加行为不端的代码:

    stimulus: 'stimulus',
    type: "callbackImageKeyboardResponsePlugin",
    timeline: targets,
    on_start: function() {
      console.log(this.stimulus)
    },
    trial_duration: function () {
      return jsPsych.randomization.sampleWithoutReplacement(
        [250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750],
        1
      )[0];
    },
    stimulus_duration: stim_duration,
    post_trial_gap: post_trial_gap(),
    
  };

编辑:我相信这里是 on_start 被调用的地方......它是我正在使用的包中插件的一部分:

      trial.on_start.call();
    } else if (typeof trial.on_start !== "undefined") {
      trial.data["on_start"] = trial.on_start;
    }

【问题讨论】:

  • 可能是因为箭头函数的误用。给我们看一些代码?
  • @AKX 忘记添加图片了,抱歉!
  • 同意我们需要一些代码。箭头函数畸形或数组越界
  • 你是如何调用 on_start() 的?请也分享该代码。
  • 代码图像无用。我们无法从图像中复制和粘贴文本。

标签: javascript reactjs typeerror


【解决方案1】:

call()不是玩具,不要无故使用,使用时要正确使用

call() 方法调用具有给定 this 值和单独提供的参数的函数。

[...]

如果方法是非严格模式下的函数,nullundefined将被替换为全局对象,原始值将转换为对象。

这就是trial.on_start.call() 没有的,指定this 参数,显然您的代码在严格模式下运行:

function test() {
  "use strict";
  const myobj = {
    x: function() {
      console.log(this);
    }
  };

  myobj.x();              // <-- this is how normally you call a method, just ()
  myobj.x.call();         // <-- the one producing undefined
  myobj.x.call(myobj);    // <-- overcomplicated, but works again
}
test();

【讨论】:

  • 感谢您的解释。使用call()时会小心!
猜你喜欢
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 2019-08-19
  • 1970-01-01
相关资源
最近更新 更多