【问题标题】:Use arrow function as method passed to requestAnimationFrame使用箭头函数作为传递给 requestAnimationFrame 的方法
【发布时间】:2018-02-06 10:22:29
【问题描述】:

我有一个带有方法的对象,该方法将传递给 requestAnimationFrame。 目前我创建对象而不是使用它返回的箭头函数重新分配方法。

var player={fn:function(){return ()=>{game.circle(this.x,this.y,this.radius)}},
x:200,y:300,radius:20};
player.fn=player.fn();

创建对象后不重新分配方法可以做到吗?

【问题讨论】:

    标签: javascript arrow-functions this-keyword


    【解决方案1】:

    你可以use a static reference to player instead:

    const player = {
      fn() {
        game.circle(player.x, player.y, player.radius);
      },
      x:200,
      y:300,
      radius:20
    };
    requestAnimationFrame(player.fn);
    

    但是不行,否则没有单独的分配就没有办法写这个。然而,通常你在调用requestAnimationFrame 时只会bind or use the arrow function

    var player = {
      fn() {
        game.circle(this.x, this.y, this.radius);
      },
      x:200,
      y:300,
      radius:20
    };
    requestAnimationFrame(() => player.fn());
    

    【讨论】:

    • 虽然你的回答会起作用,但我正在传递请求动画帧的方法,但它不起作用,但是你的绑定链接应该可以正常工作,谢谢
    • @user7951676 好吧,您没有在问题中显示您的那部分代码,所以我无法提供建议
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 2018-06-26
    • 1970-01-01
    • 2015-01-25
    • 2016-11-18
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多