我的问题很简单。基本上,我有一个 Controller 和一个 View 类。当我点击一个按钮时, Controller 告诉 View 显示一个东西。问题是, Controller 不能。这是代码。
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();
}
}
其结果是一个
Uncaught TypeError: Cannot read property 'drawThing' of undefined
at Controller.doThing (Controller.js:17)
at HTMLButtonElement.Controller.button.addEventListener (Controller.js:12)
最佳答案
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);
}
}
关于javascript - 在 es6 中调用另一个类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209447/