【问题标题】:Javascript closure (this) [duplicate]Javascript闭包(这个)[重复]
【发布时间】:2016-09-07 22:21:10
【问题描述】:

我已经在 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 对象。这个跟闭包有关系,但是我不是很明白

不知道怎么解决:/

【问题讨论】:

    标签: javascript closures this


    【解决方案1】:

    箭头函数将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();
    }
    

    【讨论】:

    • 或者简洁的方法声明:update() {
    【解决方案2】:

    箭头函数在声明时保留this 的值。

    使用正则函数表达式。不要为此使用箭头函数。

    preload: function preload () { 
        // etc
    }
    

    【讨论】:

      【解决方案3】:

      箭头函数具有词法范围this。您需要在您的情况下使用常规函数,以便 this 像往常一样绑定。变化:

      update: () => {
      

      收件人:

      update: function ( ) {
      

      scyla 的其他属性也是如此。

      【讨论】:

        猜你喜欢
        • 2013-12-25
        • 1970-01-01
        • 2011-07-22
        • 1970-01-01
        • 1970-01-01
        • 2016-04-28
        • 2012-02-05
        • 1970-01-01
        相关资源
        最近更新 更多