繁体   English   中英

从类构造函数调用函数

[英]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.xCoordsthis.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM