简体   繁体   English

从类构造函数调用函数

[英]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. 注意,我正在使用此类,并且我想调用类方法mapCoords()但是当我从构造函数中调用它时,它什么也没做。 When it is called from the show() function, it works, though; 但是,当从show()函数调用它时,它将起作用。

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. 问题是地图功能(它是p5.js库的一部分)无法正常工作。 When call mapCoords() from the constructor, this.xCoords and this.yCoords are NaN. 从构造函数调用mapCoords()时, this.xCoordsthis.yCoords为NaN。 but when I call the exact same function with the exact same code from show() the coords are calculated correctly. 但是,当我使用show()的完全相同的代码调用完全相同的函数时,坐标会正确计算。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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