英文:
Invalid left-hand side in assignment in constructor
问题
如果我试图创建一个玩家,我可以这样做
let player = game.add.sprite(100, 100, 'player');
player.speed = 4;
player.gravity = 1;
我可以将这个转化为构造函数,像这样
let player = new Player(100, 100);
function Player(x, y) {
this = game.add.sprite(x, y, 'player');
this.speed = 4;
this.gravity = 1;
}
分配this.speed和this.gravity可以正常工作,但分配this会返回`Uncaught SyntaxError: Invalid left-hand side in assignment`
英文:
If I'm trying to make a player, I could do it like this
let player = game.add.sprite(100, 100, 'player');
player.speed = 4;
player.gravity = 1;
I could turn this into a constructor function like this
let player = new Player(100, 100);
function Player(x, y) {
this = game.add.sprite(x, y, 'player');
this.speed = 4;
this.gravity = 1;
}
assigning this.speed and this.gravity work fine, but assigning this returns Uncaught SyntaxError: Invalid left-hand side in assignment
答案1
得分: 1
如果你真的想要这样做,你可以像这样做:
function Player(x, y) {
let p = game.add.sprite(x, y, 'player');
p.speed = 4;
return p;
}
let player = new Player(100, 100);
但是,有两个问题,为什么你想要这样做?你使用的是哪个Phaser版本?可能有更好的解决方案,比如继承/扩展。
对于Phaser CE / 2,请查看此示例官方示例。
对于Phaser 3,请查看此示例官方示例。
你需要根据你的具体情况来调整这些示例,但它们展示了如何工作。
英文:
If you really want, to do this you could do something like this
function Player(x, y) {
let p = game.add.sprite(x, y, 'player');
p.speed = 4;
return p;
}
let player = new Player(100, 100);
BUT two questions, why do you want to do this? and which phaser Version are you using? There might be better solutions, like inheritance / extending.
For Phaser CE / 2: checkout this example offical example
For Phaser 3: checkout this example offical example
> You would have to adapt the examples to your specific case, but they show how it can work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论