在P5JS中访问类属性总是返回false



我有一个游戏在P5.JS,我想暂停。我的大部分代码都在class中。该类的isPaused字段在构造函数中设置为false。现在,我有一个按钮来翻转这个值,像这样:this.buttonP.mousePressed(function () {this.isPaused = !this.isPaused;});。当我从类内部打印值时,值被适当地翻转。然而,当我试图从绘制函数访问isPaused属性时,这是在primary.js文件中,值总是假的。下面是部分代码:

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不再引用类上下文。您应该使用匿名函数,因为它们在封闭作用域上下文中(这里的类)操作,或者将类上下文保存在变量中,如下所示:

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

更多的阅读

最新更新