在 P5JS 中访问 class 属性 总是 returns false

Accessing class property always returns false in P5JS

我在 P5.JS 有一款游戏想暂停。我的大部分代码都在 class 中。此 class 有一个 isPaused 字段,在构造函数中设置为 false。现在,我有一个翻转此值的按钮,如下所示: this.buttonP.mousePressed(function () {this.isPaused = !this.isPaused;});。当我从 class 中打印值时,该值被适当地翻转。但是,当我尝试从 primary.js 文件中的 draw 函数访问 isPaused 属性 时,该值始终为 false。 这是代码的一部分:

let game;

function setup() {
    createCanvas(scale * factor + 1000, scale * factor);
    game = new CellularAutomaton(RULESETS.DAY_AND_NIGHT, 90, 0);
    game.setupButton();
    game.initField();
}

function draw() {
    if (!game.isPaused){
        game.updateField();
    }
}

class CellularAutomaton
{
    generation = 0;
    field = [];
    colorfield = [];
    born = [];
    survive = [];
    scale = 0;
    active = 0;
    factor = 15;
    movement = 0;
    isPaused;
    buttonR;
    buttomP;

    constructor(rule, scale, movement)
    {
        var tempborn = rule.split('/')[0];
        var tempsurvive = rule.split('/')[1];
        this.born = tempborn.split('');
        this.survive = tempsurvive.split('');
        this.born.shift();
        this.survive.shift();
        for (var i = 0; i < this.born.length; i++) this.born[i] = +this.born[i];
        for (var i = 0; i < this.survive.length; i++) this.survive[i] = +this.survive[i];
        this.scale = scale;
        this.movement = movement;
        this.isPaused = false;
    }
    setupButton(){
        this.buttonP = createButton('Pause');
        this.buttonP.position(this.scale * this.factor + 100, 500)
        this.buttonP.size(width/8 + 30, height/8);
        this.buttonP.mousePressed(function () {this.isPaused = !this.isPaused;});
        this.buttonP.style('background-color', color(0,0,255));
        this.buttonP.style('font-size', 100)
    
        this.buttonR = createButton('Restart');
        this.buttonR.position(this.scale * this.factor + 500, 500)
        this.buttonR.size(width/8 + 30, height/8);
        this.buttonR.mousePressed(this.initField);
        this.buttonR.style('background-color', color(0,0,255));
        this.buttonR.style('font-size', 100)
    }

使用 function 创建一个具有适当上下文的新作用域,因此函数中使用的 this 不再引用 class 上下文。您应该使用匿名函数,因为它们在封闭范围上下文(此处的 class )中运行,或者将 class 上下文保存在这样的变量中:

// create a new context, not accessing this.isPaused from class anymore
this.buttonP.mousePressed(function () {this.isPaused = !this.isPaused;});

// dos not create a new context then can access isPaused from current class context
this.buttonP.mousePressed() => this.isPaused = !this.isPaused;);

// or
const that = this;
this.buttonP.mousePressed(function () {that.isPaused = !that.isPaused;});

More reading