gpt4 book ai didi

JavaScript 闭包(this)

转载 作者:行者123 更新时间:2023-12-03 06:09:27 28 4
gpt4 key购买 nike

我已经在 stackoverflow 上到处查找,但找不到任何答案。

未捕获的类型错误:this.rsGame 不是一个函数(与 this.addEnemy 相同)

let game = new Phaser.Game(600,600);
let speed = 500;


let scyla = {

preload: () => {
game.load.image('bg', 'assets/bg.png');
game.load.image('pl', 'assets/pl.png');
game.load.image('enemy', 'assets/enemy.png');

},
create: () => {

game.physics.startSystem(Phaser.Physics.ARCADE)

game.add.sprite(0,0, 'bg');

this.player = game.add.sprite(300, 500, 'pl');
this.player.anchor.set(0.5);

game.physics.arcade.enable(this.player);
this.cursors = game.input.keyboard.createCursorKeys();

this.enemies = game.add.group();

// this.timer = game.time.events.loop(200, this.addEnemy(), this);
},
update: () => {

this.player.body.velocity.x = 0;
this.player.body.velocity.y = 0;

if (this.cursors.left.isDown)
this.player.body.velocity.x = speed * -1;

if (this.cursors.right.isDown)
this.player.body.velocity.x = speed;

if (this.cursors.up.isDown)
this.player.body.velocity.y = speed * -1;

if (this.cursors.down.isDown)
this.player.body.velocity.y = speed;

if (this.player.inWorld === false)
this.rsGame();
},
rsGame: () => {
game.state.start('scyla');

},
addEnemy: () => {
let enemy = game.add.sprite(300, 100, 'enemy');
game.physics.arcade.enable(enemy);
enemy.body.gravity.y = 200;

this.enemies.add(enemy);
enemy.checkWorldBounds = true;
enemy.outOfBoundsKill = true;
}
}

game.state.add('scyla', scyla);
game.state.start('scyla');

我尝试过类似的事情

let self = this

无论如何,这都会返回 windows 对象。这个和闭包有关系,但是不太明白

不知道如何解决这个问题:/

最佳答案

箭头函数将 this 设置为词法范围。您正在尝试访问 scyla 对象,但箭头函数将其设置为 window (或任何 this 等于当时的值)你声明了scyla)。

直接引用scyla:

scyla.rsGame();

或者使用标准函数表达式编写您的方法:

update: function() {
...
if (this.player.inWorld === false)
this.rsGame();
}

或简写方法声明:

update() {
...
if (this.player.inWorld === false)
this.rsGame();
}

关于JavaScript 闭包(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39379869/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com