从es6中的另一个类调用函数

时间:2016-12-18 14:43:00

标签: javascript class oop model-view-controller ecmascript-6

我的问题非常简单。基本上,我有一个Controller和一个View类。当我单击一个按钮时,控制器会告诉视图显示一个东西。问题是,控制器不能。这是代码。

ausgabe.ausgabe(FeldS);

结果是

class Controller {

    constructor(view) {
        view = new View();
      
        let button = document.getElementById('button');
        button.addEventListener('click', () => {
            controller.doThing();
        });
    }
    
    doThing() {
        view.drawThing(5, 5);
    }

}

class View {
    
    constructor(controller) {
        let canvas = document.getElementById('canvas');
        let pen = canvas.getContext('2d');
        
        this.controller = Controller;
        this.drawThing = drawThing();
    }

    drawThing(x, y) {
        pen.beginPath();
        pen.moveTo(0, 0);
        pen.lineTo(x, y);
        pen.stroke();
    }

}

1 个答案:

答案 0 :(得分:7)

view变量的范围仅限于构造函数。您应该使用this.view代替:

class Controller {

    constructor(view) {
        this.view = new View();

        let button = document.getElementById('button');
        button.addEventListener('click', () => {
            controller.doThing();
        });
    }

    doThing() {
        this.view.drawThing(5, 5);
    }

}