gpt4 book ai didi

javascript - 在 es6 中调用另一个类的函数

转载 作者:行者123 更新时间:2023-11-30 07:33:46 28 4
gpt4 key购买 nike

我的问题很简单。基本上,我有一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com