【问题标题】:Javascript binding issue not resolved by calling bind调用绑定未解决 Javascript 绑定问题
【发布时间】:2016-08-19 04:22:43
【问题描述】:

我试图递归调用一个函数,直到游戏结束,但是,在执行过程中,“this”被重置为“window”,这导致以下错误:“无法读取未定义的属性'step'。”

我已经尝试将有问题的行重写为

this.game.bind(this).step();

还有

this.game.step.bind(this);

两者都不起作用。对于上下文,step 只是一个函数,它在 Game 中调用两个帮助器来移动对象并寻找碰撞,当我使用它们而不是 step 时,错误仍然存​​在。

/* globals key */
const Game = require('./game.js');
let speed = 1;


function GameView(ctx) {
  this.ctx = ctx;
  this.game = new Game();
}

GameView.prototype.start = function (callback) {
  // let that = this
  this.bindKeyHandlers();
  this.animate(0);
};

GameView.prototype.animate = function(time) {

    speed += 1;
    if (speed >= 605) {
      speed = 0;
    };

    this.game.step();
    this.game.draw(this.ctx, speed);
    if(!this.game.lose()){
      requestAnimationFrame(this.animate());
    }
    else {
    this.ctx.fillStyle = "white";
    this.ctx.font = "italic "+24+"pt Arial ";
    this.ctx.fillText(`Game Over \n Press Enter to restart`, 100,200 );
      key('enter', ()=>{
        this.game = new Game();
        this.start();
      });
    }
};


GameView.prototype.bindKeyHandlers = function() {
  key('d', () => {
    this.game.ship.power([2, 0]);
  });
  key('a', () => {
    this.game.ship.power([-2, 0]);
  });
  key('s', () => {
    this.game.ship.power([0, 2]);
  });
  key('w', () => {
    this.game.ship.power([0, -2]);
  });
  key('l', () => {
    this.game.ship.fireBullet();
  });
};


module.exports = GameView;

【问题讨论】:

  • .bind() 在哪里使用 javascript?传递给requestAnimationFrame 的参数应该是对函数的引用吗?
  • 你确定new Game()正在生成一个对象吗?
  • 您是否意识到.bind() 返回一个您需要调用的新函数?您尝试的两个示例实际上都没有调用.bind() 返回的函数。
  • 应该是requestAnimationFrame(this.animate.bind(this));

标签: javascript binding this


【解决方案1】:

您的问题是animate 函数的this 没有引用您希望的上下文。因此,您的违规线路(或缺少线路)完全在其他地方。

Function.bind 返回一个函数,你需要在某个地方绑定这个新的函数,而构造函数是完美的地方。这是一个例子:

function GameView(ctx) {
  this.ctx = ctx;
  this.game = new Game();
  this.animate = this.animate.bind(this)
}

查看此jsfiddle 了解更多信息,记得打开您的开发者控制台来见证调用notBound 时出现的错误

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2018-09-28
    相关资源
    最近更新 更多