admin管理员组文章数量:1394381
My problem is very simple. Basically, I have a Controller and a View class. When I click a button, the controller tells the view to display a thing. Problem is, the Controller can't. Here's the code.
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();
}
}
My problem is very simple. Basically, I have a Controller and a View class. When I click a button, the controller tells the view to display a thing. Problem is, the Controller can't. Here's the code.
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();
}
}
The result of which is an
Uncaught TypeError: Cannot read property 'drawThing' of undefined
at Controller.doThing (Controller.js:17)
at HTMLButtonElement.Controller.button.addEventListener (Controller.js:12)
Share
Improve this question
asked Dec 18, 2016 at 14:43
a.aneva.anev
1352 gold badges4 silver badges11 bronze badges
1 Answer
Reset to default 7The view
variable is scoped only to the constructor. You should use this.view
instead:
class Controller {
constructor(view) {
this.view = new View();
let button = document.getElementById('button');
button.addEventListener('click', () => {
controller.doThing();
});
}
doThing() {
this.view.drawThing(5, 5);
}
}
本文标签: javascriptCalling up functions from another class in es6Stack Overflow
版权声明:本文标题:javascript - Calling up functions from another class in es6 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744621568a2616057.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论