简体   繁体   中英

Call a function from a class constructor

I'm using this class, Note, and I want to call the class method mapCoords() but it doesn't do anything when I'm calling it from the constructor. When it is called from the show() function, it works, though;

Is it possible to call functions from the constructor ?

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);
    }
}

UPDATE : Okay, the function is called correctly from the constructor. the problem is the map function (which is part of the p5.js library) which doesn't do its job. When call mapCoords() from the constructor, this.xCoords and this.yCoords are NaN. but when I call the exact same function with the exact same code from show() the coords are calculated correctly.

It is called correctly, you can try to run it.

What it does mean "doesn't seem to do anything"

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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