【问题标题】:Error accessing object property in module访问模块中的对象属性时出错
【发布时间】:2018-07-18 21:31:02
【问题描述】:

我目前正在使用 JavaScript 模块运行一些测试,不幸的是,在尝试设置 mychart 对象的属性 setOption 时出现 Uncaught TypeError 错误。这作为参数传递给另一个模块中的类。当前代码如下所示:

App.js

import {   echart,   theme,   option } from './module-chart';

import {   ChartController } from './module-chart-controller';

let mychart = echart.init(document.getElementById('main'), theme); 
mychart.setOption(option);

let chartController = new ChartController(mychart); 
chartController.animateChart();

模块图表控制器.js

class ChartController{

  constructor(chart){
    this.mychart = chart;
  }

  animateChart() {
    let intervalo = setInterval(function() {
      concentrationOfAandB = getObjectConcentrationOfAandB();
      dataA.push(concentrationOfAandB.concentrationOfA);
      dataB.push(concentrationOfAandB.concentrationOfB);
      this.mychart.setOption({
        series: [{
            data: dataA,
            animationDuration: 1000
          },
          {
            data: dataB,
            animationDuration: 1000
          }
        ]
      });
    }, 1900);
    setTimeout(function() {
      clearInterval(intervalo);
    }, 40000);
  }
}
export {ChartController};

当我在App.js文件中传递module-chart-controller.js代码时,没有出现错误。

控制台显示如下错误信息:Uncaught TypeError: Can not read property 'setOption' of undefined. 指责module-chart-controller.js文件出错

提前感谢您的关注!

【问题讨论】:

    标签: javascript ecmascript-6 es6-class es6-modules


    【解决方案1】:

    您需要bind 请求分配给this 的属性的方法,以便该方法可以访问它们。同样你需要做setInterval函数,它需要访问this,所以你也需要bind它。

    constructor(chart){
        this.mychart = chart;
        this.animateChart = this.animateChart.bind(this);
    }
    
    animateChart() {
        let intervalo = setInterval(function() {
           concentrationOfAandB = getObjectConcentrationOfAandB();
           dataA.push(concentrationOfAandB.concentrationOfA);
           dataB.push(concentrationOfAandB.concentrationOfB);
           this.mychart.setOption({
               series: [{
                   data: dataA,
                   animationDuration: 1000
               },
               {
                   data: dataB,
                   animationDuration: 1000
               }]
           });
        }.bind(this), 1900);
    
        setTimeout(function() {
            clearInterval(intervalo);
        }, 40000);
    }
    

    【讨论】:

    • 你还需要bind setInterval 函数。我更新了我的答案。
    • 感谢您的解决方案!帮助很大
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多