[英]Call a function from a class constructor
注意,我正在使用此類,並且我想調用類方法mapCoords()
但是當我從構造函數中調用它時,它什么也沒做。 但是,當從show()函數調用它時,它將起作用。
是否可以從構造函數中調用函數?
class Note {
constructor(aName, aPosX, aPosY, aIsTonic) {
this.name = aName;
this.x = aPosX;
this.y = aPosY;
this.xCoords;
this.yCoords;
this.radius = 15;
this.isTonic = aIsTonic;
this.mapCoords();
}
show() {
this.mapCoords();
ellipse (this.xCoords, this.yCoords, this.radius * 2);
text(this.name, this.xCoords, this.yCoords);
}
mapCoords() {
this.xCoords = map(this.x, 0, maxNumberOfScales - 1, margin, width - margin);
this.yCoords = map(this.y, 0, 12, height - margin, margin);
}
}
更新:好的,可以從構造函數中正確調用該函數。 問題是地圖功能(它是p5.js庫的一部分)無法正常工作。 從構造函數調用mapCoords()時, this.xCoords
和this.yCoords
為NaN。 但是,當我使用show()
的完全相同的代碼調用完全相同的函數時,坐標會正確計算。
它被正確調用,您可以嘗試運行它。
它的意思是“似乎什么也沒做”
let maxNumberOfScales = 10; let margin = 10; let width = 10; let height = 10; class Note { constructor(aName, aPosX, aPosY, aIsTonic) { this.name = aName; this.x = aPosX; this.y = aPosY; this.xCoords; this.yCoords; this.radius = 15; this.isTonic = aIsTonic; this.mapCoords(); } show() { this.mapCoords(); ellipse (this.xCoords, this.yCoords, this.radius * 2); text(this.name, this.xCoords, this.yCoords); } mapCoords() { console.log('It is here, learn to use console.log :)'); this.xCoords = map(this.x, 0, maxNumberOfScales - 1, margin, width - margin); this.yCoords = map(this.y, 0, 12, height - margin, margin); } } function map(){} new Note('a', 1, 2, true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.