【问题标题】:Returning hash of static functions is empty object返回静态函数的哈希是空对象
【发布时间】:2016-10-29 17:07:18
【问题描述】:

我正在尝试根据键动态调用绘图函数。

当我注销 renderFunctions 时,它显示为空 Object {}。

我希望这些功能包含在“ship”和“ball”键的内部。

    class Render {
      static renderFunctions() {
        return {
          'ship': this.drawShip,
          'ball': this.drawBall
        };
      }

      static render(key, ls, context, portal) {
        let renderFns = this.renderFunctions();
        console.log(renderFns);
      }

      static drawShip(ctx, p, t) {
        p.drawRect(ctx, t.x - 5, t.y - 100, 10, 100, t.teamColor);
      }

      static drawBall(ctx, p, t) {
        ctx.arc(t.x, t.y, 7, 0, 2 * Math.PI, false);
        ctx.fillStyle = t.teamColor;
        ctx.fill();
      }
    }

为什么我的功能没有显示?

【问题讨论】:

    标签: javascript static ecmascript-6


    【解决方案1】:

    您不应将静态函数称为this 的属性,而应将其称为您的类的属性(即Render)。

    class Render {
        static renderFunctions() {
            return {'ship' : Render.drawShip,
           'ball' : Render.drawBall};
        }
    
        static render(key, ls, context, portal) {
            let renderFns = Render.renderFunctions();
            console.log(renderFns);
        }
    
        static drawShip(ctx, p, t) {
            p.drawRect(ctx, t.x - 5, t.y - 100, 10, 100, t.teamColor);
        }
    
        static drawBall(ctx, p, t) {
            ctx.arc(t.x, t.y, 7, 0, 2 * Math.PI, false);
            ctx.fillStyle = t.teamColor;
            ctx.fill();
        }
    }
    

    【讨论】:

    • @quantumpotato 尝试在控制台中单击 Object {},您应该会看到您的功能。
    • 然后我可以直接用 renderFns[key]( ... ) 调用它们?
    • @quantumpotato 是的。例如,您可以使用renderFns.ship(...)renderFns['ball'](...)
    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多