构造函数中的赋值操作左侧无效

huangapple go评论63阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月8日 23:28:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定