【问题标题】:Javascript Inheritance with 3 separated files带有 3 个分隔文件的 Javascript 继承
【发布时间】:2012-09-29 20:31:23
【问题描述】:

您好,我有 3 个 javascript 文件:Game.js、Player.js、Drawable.js。 现在在 Game.js 中,我想创建一个对象 _player,它是 Drawable,然后是 Player。这意味着 _player 是一个 Player Object,即 EXTENDS Drawable 的类。

Drawable.js

function Drawable(x, y, src)
{
  this.x = x;
  this.y = y;
  this.img = new Image();
  this.img.src = src;
  this.width = this.img.width;
  this.height = this.img.height;

  this.draw = function(canvas) 
  {   
    canvas.drawImage(this.img,this.x, this.y);
  }

  this.midpoint = function() 
  {
    return {
      x: this.x + this.width/2,
      y: this.y + this.height/2};
    }

  }
}

Player.js

function Player()
{
  this.moveLeft = function()
  {
    this.x -= 3;
  }

  this.moveRight = function()
  {
    this.x += 3;
  }

  this.moveUp = function() 
  {
    this.y -= 3;
  }

  this.moveDown = function()
  {
    this.y += 3;
  }
}

Game.js

var _player;

 _player = new Player();

 _player.draw(...);
 _player.moveLeft();
 ...
 ...

这就是我想做的。我试图把 Player.prototype = new Drawable;但它不起作用。我该怎么办?

【问题讨论】:

    标签: javascript html inheritance


    【解决方案1】:

    如果你想让玩家对象表现得可以调用

    player.draw(...);
    player.moveLeft(...);
    

    那么draw 和moveLeft 函数需要作为属性存储在每个玩家对象(yikes)或玩家对象原型链的某个位置。

    这对您的实际代码提出了一条评论:这些函数应该在原型中,而不是实际的对象中。

    所以,回答你的实际问题...

    • 您应该做的第一件事是将方法放在原型中。

    • 然后你需要让玩家原型的原型成为所有可绘制对象的原型。

    这可能听起来令人困惑,但这是金钱线:

    Player.prototype = Object.create(Drawable.prototype);
    

    在使用new Player 创建玩家之前执行此操作。 :)

    附录

    Live Demo -- 它还向您展示了如何执行“构造函数”,以便您可以使用初始 x 和 y 构建播放器。

    【讨论】:

      【解决方案2】:

      Coffeescript 是一种具有基于类的对象模型的语言,该对象模型是在 javascript 的原型对象模型之上建模的。在他们的页面上,您可以在 coffeescript 中看到一个示例 how the extends keyword works,当它编译为 javascript 时。

      【讨论】:

        【解决方案3】:

        这可能不是您的考虑因素。也许你从来没有考虑过这件事,但为什么不制作一个Drawable 组件,通过依赖注入将其提供给玩家,无论是在构建期间还是之后不久。

        var Drawable = function () { ... };
        var Player = function () { ... };
        
        
        var player = new Player(new Drawable(), new Controlable(), new Physical());
        

        【讨论】:

          猜你喜欢
          • 2017-08-03
          • 2013-10-02
          • 1970-01-01
          • 1970-01-01
          • 2012-11-17
          • 1970-01-01
          • 2011-06-12
          • 1970-01-01
          • 2011-01-27
          相关资源
          最近更新 更多