我有一个类TextManager的对象,它有一些数字xx ,它在构造函数中最初设置为零。 我希望能够在文本区域发生变化时更新对象的xx变量。
class Drawer { canvasElement: HTMLCanvasElement; constructor(_canvasElement: HTMLCanvasElement) { this.canvasElement = _canvasElement; } drawCircle(x:number,y:number,radius:number,color:string) { var ctx = this.canvasElement.getContext("2d"); ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.fillStyle = color; ctx.closePath(); ctx.fill(); } } var canv; var drawer; var d = 0; var textAreaElement; var textManager; class TextManager{ textAreaElement: HTMLAreaElement; xx: number; constructor(_textAreaElement: HTMLAreaElement) { this.textAreaElement = _textAreaElement; this.xx = 0; this.textAreaElement.onchange = this.update; } update() { this.xx += 10; if (this.xx > 50) this.xx = 0; drawer.drawCircle(95 + this.xx, 50, 40, "#FF0000"); } } window.onload = () => { canv = <HTMLCanvasElement>document.getElementById("myCanvas"); drawer = new Drawer(canv); textAreaElement = <HTMLAreaElement>document.getElementById("codeArea"); textManager = new TextManager(textAreaElement); };问题是在代码中使用这种方式会导致xx = NaN 。 因为我认为它不是访问成员,它只是访问类中的函数。
如何在每次事件发生时更新对象的xx ?
I have an object of class TextManager, it has some number xx which is set initially to zero in the constructor. I want to be able to update the object's xx variable whenever the text area changes.
class Drawer { canvasElement: HTMLCanvasElement; constructor(_canvasElement: HTMLCanvasElement) { this.canvasElement = _canvasElement; } drawCircle(x:number,y:number,radius:number,color:string) { var ctx = this.canvasElement.getContext("2d"); ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.fillStyle = color; ctx.closePath(); ctx.fill(); } } var canv; var drawer; var d = 0; var textAreaElement; var textManager; class TextManager{ textAreaElement: HTMLAreaElement; xx: number; constructor(_textAreaElement: HTMLAreaElement) { this.textAreaElement = _textAreaElement; this.xx = 0; this.textAreaElement.onchange = this.update; } update() { this.xx += 10; if (this.xx > 50) this.xx = 0; drawer.drawCircle(95 + this.xx, 50, 40, "#FF0000"); } } window.onload = () => { canv = <HTMLCanvasElement>document.getElementById("myCanvas"); drawer = new Drawer(canv); textAreaElement = <HTMLAreaElement>document.getElementById("codeArea"); textManager = new TextManager(textAreaElement); };The problem is that using this way in the code results in xx = NaN. As i think it's not accessing the member, it's just accessing the function inside the class.
How can i update the object's xx with each event occurrence ?
最满意答案
您需要在update方法中捕获所需的this值。 最容易修复就是改变
this.textAreaElement.onchange = this.update;至
this.textAreaElement.onchange = () => this.update();You need to capture the this value that you want in the update method. Easiest fix would be to change
this.textAreaElement.onchange = this.update;to
this.textAreaElement.onchange = () => this.update();更多推荐
xx,class,textAreaElement,TextManager,number,电脑培训,计算机培训,IT培训"/> <m
发布评论